虽然整个解决方案是不好的,你可以有一个私人的静态方法,这是在每个其他的公共静态方法中调用。
这不是一个构造函数,它通常是因为构造函数用于构造和对象,而在静态上下文中没有。
因此,对于每个静态调用后发射一个共同的功能,你可以使用:
class Example {
private static function common() {
echo 'called';
}
public static function method1() {
self::common();
echo "</br> method1;";
}
public static function method2() {
self::common();
echo "</br> method2;";
}
}
Example::method2();
导致成
called
method2;
您也可以建立自己的对象为静态方法
class Example {
private function __construct() {
echo 'contructor called';
}
public static function method1() {
$self = new self();
echo "</br> method1;";
}
public static function method2() {
$self = new self();
echo "</br> method2;";
}
}
Example::method1();
结果为:
contructor called
method1;
这里的问题是,每个方法都会新建构造函数的实例。
您可以按照建议使用Singleton模式,以便在所有静态方法中共享该类的实例。
class Example {
private static $_inst = null;
private $_x = 0;
private function __construct() {
echo 'contructor called';
}
private static function getInstance() {
if(self::$_inst == null) {
self::$_inst = new self();
}
return self::$_inst;
}
public static function method1() {
self::getInstance();
self::getInstance()->_x = 100;
echo "</br> method1;";
}
public static function method2() {
self::getInstance();
echo self::getInstance()->_x;
echo "</br> method2;";
}
}
Example::method1();
Example::method2();
这将导致到:
contructor called
method1;100
method2;
所以实例变量$_x
的保存时method2()
被调用,但构造不叫第二次,你可以看到价值只有一个contructor called
在结果中。
而且,要重复一下自己,这个想法是非常可怕的。
你能举个例子吗? – Speedwheelftw
@ user3540050当像'Example :: method1()'这样的静态表示法被弃用时?任何证据? – hindmost