【问题标题】:PHP 5.2 Equivalent to Late Static Binding (new static)?PHP 5.2 等效于后期静态绑定(新静态)?
【发布时间】:2011-07-08 23:07:15
【问题描述】:

我正在尝试使为 php 5.3 构建的脚本在 php 5.2 服务器上工作。该脚本使用了很多后期静态绑定,例如:

return new static($options);

什么是 php 5.2 中的 this 等价物?它会以某种方式成为新的自我吗?还是不能达到同样的效果...

谢谢

编辑:

这是一个相关的问题New self vs. new static

只是想把我的头包裹在这个后期静态绑定的东西上......

【问题讨论】:

  • 恐怕没有等价物,后期静态绑定只在 PHP 5.3 中引入。
  • 这看起来像单身:X
  • 就像@Robin 所说,没有等价物。也许 get_class() 可以帮助你达到类似的结果?

标签: php late-static-binding


【解决方案1】:

我认为唯一的方法是通过一个受保护的静态方法来构建你的单例和一个定义要使用的类的公共静态方法。 您可以通过在 $this 上使用 get_class 函数来“模拟”它

class ParentClass{
    protected static function getInstance2($className){
         //some stuffs here
         return new $className();
    }
    public static function getInstance(){
        return self::getInstance2(get_class(self));
    }
}
class ChildClass extends ParentClass{
    public static function getInstance(){
        return self::getInstance2(get_class(self));
    }
}

【讨论】:

    猜你喜欢
    • 2012-04-21
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    相关资源
    最近更新 更多