PHP 5.2 Equivalent to Late Static Binding (new static)?

强颜欢笑 提交于 2019-12-19 19:45:26

问题


I am trying to make a script that is built for php 5.3 work on a php 5.2 server. The script uses a lot of late static binding like:

return new static($options);

What is the equivalent to this in php 5.2? would it be new self somehow? Or is it not possible to achieve the same effect...

Thanks

EDIT:

Here is a related question New self vs. new static

Juts trying to wrap my head around this late static binding stuff...


回答1:


I think the only way is to pass by a protected static method that build your singleton and a public static method that defines the class to use. You can "emulate" it by using the get_class function over $this

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));
    }
}


来源:https://stackoverflow.com/questions/5196476/php-5-2-equivalent-to-late-static-binding-new-static

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!