运行 代码在 PHP 一次

Running code in a PHP once

我正在尝试在 PHP 中编写一个 class 作为命令行工具集合的包装器,使它们更易于从 PHP 中使用。

我在文件 myclass.php.

中有一个 class (MyClass)

我有代码检查是否安装了所需的工具,然后将常量 (TOOLS_AVAILABLE) 设置为 truefalse。虽然它不是很多代码,但我只希望它 运行 第一次有人试图实例化我的 class 使用它的任何静态函数。处理此问题的最佳做法是什么?

您需要在您的 class 中创建一个 __construct 函数,并将您想要在实例化时执行的任何代码放在那里:

class MyClass {
    function __construct(/* arguments */) {
        /* your code here */
    }
}

当有人实例化 class 时,代码将只执行一次。

I only want it to run the first time somebody tries to instantiate my class or use any of its static functions.

嗯,最好的答案是不要有任何静态方法。然后,您可以按照@treegarden 的回答将代码粘贴到构造方法中。

如果您必须有静态方法,那么您需要在 class 中使用静态标志来指示您何时调用 'run once'代码,所以你可以避免再次 运行 它。然后从每个静态方法和构造函数中显式调用它。像这样:

<?php
class myClass {
    private static $hasRunOnce = false;

    private static runMeOnce()
    {
        if (!self::$hasRunOnce) {
            self::$hasRunOnce = true;
            //put your 'run once' code here...
        }
    }

    public static oneOfYourStaticMethods()
    {
        self::runMeOnce();
        //put your static method code here...
        //this would be the same for each of your static methods and your constructor.
    }
}

希望对您有所帮助。