Home >Backend Development >PHP Tutorial >Detailed explanation of problems encountered in inheritance of PHP singleton mode
Detailed explanation of PHPSingle case modeInheritanceProblems encountered
<?php // 单例模式之继承 class Singleton { protected static $ins = null; private final function construct() { } protected final function clone() { } // public static function getIns() { // if(self::$ins === null){ // self::$ins = new self(); // } // return self::$ins; // } public static function getIns() { if(static::$ins === null){ static::$ins = new static(); } return static::$ins; } } class Child extends Singleton { // protected static $ins = null; } /* 输出结果为: bool(true) object(Singleton)#1 (0) { } 问题:对象 $c1, $c2 竟然都是 Singleton 的实例 ??? 解决方法:将 getIns() 方法中关键字 self 替换为 static, 利用后期静态绑定的特性 */ $c1 = Child::getIns(); $c2 = Child::getIns(); var_dump($c1 === $c2); //true var_dump($c1); // ------------------------------------------------------------------------ // 另一个问题 /* 输出结果为: bool(true) object(Child)#1 (0) { } 问题:对象 $c3 竟然是 Child 的实例, 实际上应该是 Singleton 的实例 ??? 原因:因为 $ins 属性是从父类 Singleton 继承过来的, 当第一次调用 Child::getIns() 时, $ins = new Child() 当再次调用 Singleton::getIns() 时, $ins 已经被实例过了, 而且指向 Child 的实例, 所以此时 $c3 变成了 Child 的实例 解决方法:在 Child 类中, 声明自己独有的 $ins 属性 */ $c3 = Singleton::getIns(); var_dump($c1 === $c3); var_dump($c3);
The getIns() method of late static binding There is another problem:
If the $ins property of Singleton is set to private, the subclass Child must set its own $ins property,
Because static::$ins first looks for the subclass's own $ins attribute, but since the subclass is not declared and the parent class cannot inherit it, Child::getIns() is called at this time
The method will report an error:
Fatal error: Cannot access property Child::$ins in D:\wamp\www\mycode\DesignPattern\Singleton.php on line 27
Solution:
#Set the $ins attribute of the parent class Singleton to protected or set the subclass Child's own $ins Attributes
The above is the detailed content of Detailed explanation of problems encountered in inheritance of PHP singleton mode. For more information, please follow other related articles on the PHP Chinese website!