Work with classes in PHP

Let's say I have the following class:

class Test
{
    function __construct()
    {
        // initialize some variable

        $this->run();
    }

    function run()
    {
        // do some stuff

        $this->handle();
    }

    function handle()
    {
    }
}

Normally I would create an instance like:

$test = new Test();

However, I really do not need $testanywhere, since the functions in the class do all the work once and after that I will no longer need an instance of the class.

What should I do in this situation or should I only do: $test = new Test();

I hope that what I try to say, if not, please, makes sense.

+5
source share
5 answers

They should probably be static functions if they don't need an instance of the instance:

class Test
{
    private static $var1;
    private static $var2;

    // Constructor is not used to call `run()`, 
    // though you may need it for other purposes if this class
    // has non-static methods and properties.

    // If all properties are used and discarded, they can be
    // created with an init() function
    private static function init() {
        self::$var1 = 'val1';
        self::$var2 = 'val2';
    }

    // And destroyed with a destroy() function


    // Make sure run() is a public method
    public static function run()
    {
        // Initialize
        self::init();

        // access properties
        echo self::$var1;

        // handle() is called statically
        self::handle();

        // If all done, eliminate the variables
        self::$var1 = NULL;
        self::$var2 = NULL;
    }

    // handle() may be a private method.
    private static function handle()
    {
    }
}

// called without a constructor:
Test::run();
+10
source

If you do not need it, just do:

new Test();
+3
source

(new Test()).functionHere(). Test::functionHere()

+1

. $test, , 0,001% . . - . , , . , , , , .

+1

,

new Test;

, :

class Test
{
  public static function run()
  {
    // do some stuff
    self::handle();
  }

  public static function handle()
  {
  }
}

:

Test::run();
+1

All Articles