V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
sperad
V2EX  ›  问与答

求解 PHP static 相关问题

  •  
  •   sperad · 2017-02-18 13:46:52 +08:00 · 1451 次点击
    这是一个创建于 2625 天前的主题,其中的信息可能已经有所发展或是发生改变。
    <?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?
    4 条回复    2017-02-20 09:24:47 +08:00
    vibbow
        1
    vibbow  
       2017-02-18 18:36:16 +08:00
    感觉上 B1/B2 返回不同是 Late Static Bindings 的原因。
    cloudyplain
        2
    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
        3
    sperad  
    OP
       2017-02-20 09:19:52 +08:00
    @vibbow , 不是后期绑定的原因,因为 new static() 是在 if 语句内部。
    sperad
        4
    sperad  
    OP
       2017-02-20 09:24:47 +08:00
    @cloudyplain ,谢谢大神指点 12, 你的意思是 static 作用域的不同吧,我也想过,也能解释。但在 B1,B2 分别调用 getInstance 方法时候,与 A1,A2 分别静态使用静态属性$instance 的内部处理方式一样嘛?我这里不是很清楚,
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3879 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 05:10 · PVG 13:10 · LAX 22:10 · JFK 01:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.