小编典典
self 指向其编写所在的类。
因此,如果您的getInstance方法位于类名中MyClass,则以下行:
self::$_instance = new self();
将做与:
self::$_instance = new MyClass();
编辑:评论后,还有更多信息。
如果您有两个相互扩展的类,则有两种情况:
getInstance 在子类中定义
getInstance 在父类中定义
第一种情况看起来像这样(在此示例中,我已经删除了所有不必要的代码-您必须将其重新添加来获得单例行为)*:
class MyParentClass {
}
class MyChildClass extends MyParentClass {
public static function getInstance() {
return new self();
}
}
$a = MyChildClass::getInstance();
var_dump($a);
在这里,您将获得:
object(MyChildClass)#1 (0) { }
意思self是MyChildClass-即编写它的类。
对于第二种情况,代码如下所示:
class MyParentClass {
public static function getInstance() {
return new self();
}
}
class MyChildClass extends MyParentClass {
}
$a = MyChildClass::getInstance();
var_dump($a);
这样您会得到以下输出:
object(MyParentClass)#1 (0) { }
这意味着self手段MyParentClass-即在这里也一样, 在其所在的班级 。
在PHP <5.3中,“编写它的类”很重要-有时会引起问题。
这就是PHP 5.3为static关键字引入新用法的原因:现在可以在我们self在这些示例中使用的位置准确使用它:
class MyParentClass {
public static function getInstance() {
return new static();
}
}
class MyChildClass extends MyParentClass {
}
$a = MyChildClass::getInstance();
var_dump($a);
但是,使用static代替self,您现在将获得:
object(MyChildClass)#1 (0) { }
这意味着static指向使用 的类 (我们使用MyChildClass::getInstance()),而不是指向其中 的类 。
当然,的行为self没有改变,不会破坏现有的应用程序-PHP 5.3刚刚添加了新的行为,回收了static关键字。
而且,说到PHP 5.3,您可能想看看PHP手册的Late Late
Bindings页面。
2020-05-29