求解 PHP static 相关问题

2017-02-18 13:46:52 +08:00
 sperad
<?php
class A {
public static $instance;
public static function getInstance()
{
if(null === static::$instance){
static::$instance = new static();
}
return static::$instance;
}
}
class A1 extends A {}
class A2 extends A {}

/*************************************************/
class B {
public static function getInstance()
{
static $instance;
if(null === $instance){
$instance = new static();
}
return $instance;
}
}
class B1 extends B{}
class B2 extends B{}

$a1 = A1::getInstance(); $b1 = B1::getInstance();
$a1_c = A1::getInstance(); $b1_c = B1::getInstance();
$a2 = A2::getInstance(); $b2 = B2::getInstance();
var_dump($a1, $a1_c, $a2, $b1, $b1_c, $b2);

var_dump($a1 === $a1_c); var_dump($b1 === $b1_c);
var_dump($a1 === $a2); var_dump($b1 === $b2);
请问四个结果情况如何? why?
1464 次点击
所在节点    问与答
4 条回复
vibbow
2017-02-18 18:36:16 +08:00
感觉上 B1/B2 返回不同是 Late Static Bindings 的原因。
cloudyplain
2017-02-18 19:54:27 +08:00
A 的子类没有重定义父类的$instance 变量,因此 static::$instance 只返回父类中的变量,因为 A1 先调用了 getInstance ,同时由于后期绑定的原因, getInstance 总会返回 A1 的实例。 B 方法中 static 关键字和 A 中的是两个概念, A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope 。见 http://php.net/manual/en/language.variables.scope.php
在下拙见,不正确之处还望纠正。
sperad
2017-02-20 09:19:52 +08:00
@vibbow , 不是后期绑定的原因,因为 new static() 是在 if 语句内部。
sperad
2017-02-20 09:24:47 +08:00
@cloudyplain ,谢谢大神指点 12, 你的意思是 static 作用域的不同吧,我也想过,也能解释。但在 B1,B2 分别调用 getInstance 方法时候,与 A1,A2 分别静态使用静态属性$instance 的内部处理方式一样嘛?我这里不是很清楚,

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/341387

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX