使用PHP中的类

Pee*_*Haa 5 php class

假设我有以下课程:

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

        $this->run();
    }

    function run()
    {
        // do some stuff

        $this->handle();
    }

    function handle()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

通常我会创建一个像:

$test = new Test();
Run Code Online (Sandbox Code Playgroud)

但是我并不需要$test任何地方,因为类中的函数只执行一次所有工作,之后我将不再需要该类的实例.

在这种情况下我该怎么办?或者我应该这样做: $test = new Test();

如果不是,请希望告诉我,我希望我说的是有道理的.

Mic*_*ski 9

它们应该是静态函数,如果它们不需要实例化的实例:

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();
Run Code Online (Sandbox Code Playgroud)