php new self 详解

本文深入探讨了PHP中单例模式的实现机制,通过实例分析了如何在不同类继承情况下的实例获取行为,并介绍了PHP5.3版本引入的静态关键字优化。详细解释了实例方法在类中的作用以及其对单例行为的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
self points to the class in which it is written. So, if your getInstance method is in a class name MyClass, the following line : self::$_instance = new self(); Will do the same as : self::$_instance = new MyClass(); Edit : a couple more informations, after the comments. If you have two classes that extend each other, you have two situations : getInstance is defined in the child class getInstance is defined in the parent class The first situation would look like this (I've removed all non-necessary code, for this example -- you'll have to add it back to get the singleton behavior)* :
class MyParentClass { }
class MyChildClass extends MyParentClass {
     public static function getInstance() { return new self(); }
}
$a = MyChildClass::getInstance();
 var_dump($a);
Here, you'll get : object(MyChildClass)#1 (0) { } Which means self means MyChildClass -- i.e. the class in which it is written.
 
 For the second situation, the code would look like this :
class MyParentClass {
    public static function getInstance() { return new self(); }
 }
class MyChildClass extends MyParentClass { }
$a = MyChildClass::getInstance();
var_dump($a);
And you'd get this kind of output : object(MyParentClass)#1 (0) { } Which means self means MyParentClass -- i.e. here too, the class in which it is written.
 
With PHP < 5.3, that "the class in which it is written" is important -- and can sometimes cause problems. That's why PHP 5.3 introduces a new usage for the static keyword : it can now be used exactly where we used self in those examples :
class MyParentClass {
    public static function getInstance() { return new static(); }
}
class MyChildClass extends MyParentClass { }
$a = MyChildClass::getInstance();
var_dump($a);
But, with static instead of self, you'll now get : object(MyChildClass)#1 (0) { } Which means that static sort of points to the class that is used (we used MyChildClass::getInstance()), and not the one in which it is written. Of course, the behavior of self has not been changed, to not break existing applications -- PHP 5.3 just added a new behavior, recycling the static keyword. And, speaking about PHP 5.3, you might want to take a look at the Late Static Bindings page of the PHP manual.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值