php - 在 PHP 中使用类

标签 php class

假设我有以下类(class):

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

        $this->run();
    }

    function run()
    {
        // do some stuff

        $this->handle();
    }

    function handle()
    {
    }
}

通常我会创建一个像这样的实例:

$test = new Test();

但是我真的不需要 $test 任何地方,因为类中的函数一次完成所有工作,之后我将不再需要类的实例。

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

我希望我想说的是有道理的,如果没有请告诉我。

最佳答案

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

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();

关于php - 在 PHP 中使用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7125585/

相关文章:

php - WooCommerce 序列化 wp_postmeta 表中的元值数组

c++ - 我在这里做错了什么?使用指向函数 typedef 的指针定义类。

c++ - 是否可以使用 Dtrace 探测 C++ 类中的条目?

C++ Tic-Tac-Toe 使用类

c++是否对置换算法使用类

c++ - 如何通过函数(不在任何类中)在类中使用私有(private)变量?

php - Laravel 5 $user->first()->delete() 删除所有用户

php - 使用 chr + rand 生成随机字符 (A-Z)

php - PHP中echo、echo()、print和print()的区别

php - 如何确保 php 脚本有足够的时间来执行 MySQL 查询?