PHP中的静态实例
发布时间:2020-12-13 22:07:58 所属栏目:PHP教程 来源:网络整理
导读:为什么以下代码打
为什么以下代码打印“1,1,1”而不是“4,5,6”?
class MyClass { // singleton instance private static $instance = 3; function __construct() { $instance++; echo $instance . ","; } } for($i = 0; $i < 3; $i++) { $obj = new MyClass(); } 解决方法
$instance是局部变量,而不是静态类属性.与Java不同,您始终必须访问该范围内的变量或属性
$var; // local variable $this->var; // object property self::$var; // class property 我刚看到 // singleton instance 单例模式通常实现不同 class SingletonClass { protected $instance = null; protected $var = 3; protected __construct () {} protected __clone() {} public static function getInstance () { if (is_null(self::$instance)) { self::$instance = new self(); } return self::$instance; } public function doSomething () { $this->var++; echo $this->var; } } $a = SingletonClass::getInstance(); $a->doSomething(); 单例模式确保您始终只与一个类的实例进行交互. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |