Extending PHP static classes

我的未来我决定 提交于 2019-11-30 03:45:51

Again, this is not possible prior to PHP 5.3.0.

Late Static Binding was introduced in PHP 5.3.0 and allows you to do exactly what you want via the static keyword.

class Super {
    protected static $title = 'super';
    public static function get_class_name()        
    {
        echo __CLASS__;
    }
    public static function get_title()
    {
        echo static::$title;
    }
}
class Sub extends Super {
    protected static $title = 'sub';
}

get_class_name() will still return Super though has __CLASS__ always returns the current class the method being run is declared in (kind of like __FILE__ which always returns the current file no matter if you included it or not).

For that you don't have any choice but to re-declare the function in the Sub class.

class Super {
    protected static $title = 'super';
    public static function get_class_name()        
    {
        echo __CLASS__;
    }
    public static function get_title()
    {
        echo static::$title;
    }
}
class Sub extends Super {
    protected static $title = 'sub';

    public static function get_class_name()        
    {
        echo __CLASS__;
    }
}

You can used get_called_class() to get the class name of the class you are calling, even if it is static. You don't have to declare it anywhere.

From Andrew's Example:

class Super {
    public static function get_class1_name()        
    {
        echo __CLASS__;
    }
    public static function get_title()
    {
        echo get_called_class();
    }

}
class Sub extends Super {    
    public static function get_class2_name()        
    {
        echo __CLASS__;
    }

}
Sub::get_title(); // Echos Sub.
Sub::get_class1_Name(); // echos super
Sub::get_class2_Name(); // echos sub

Therefore you don't have to declare any variables.

Fortunately, I'm doing something for me, so I said, screw it, I'm using PHP5.3. But even so, I don't like that I have to redeclare "get _class _name" in every class, maybe I'm extending like 10 classes. So I came up with this solution:

class Super {
    protected static $classname = __CLASS__;
    public static function get_classname($name)
    {
        static::$classname = $name;
    }
    public static function get_classname()
    {
        return static::$classname;
    }
}
class Sub1 extends Super { }
class Sub2 extends Super { }
class Sub3 extends Super { }

$classes = get_declared_classes();
foreach($classes as $k => $v)
{
    if (is_subclass_of($v, 'Super'))
    {
        $v::set_classname($v);
    }
}

echo Sub1::get_classname(); // Sub1
echo Sub2::get_classname(); // Sub2
echo Sub3::get_classname(); // Sub3

It might seem a little dirty, but I don't think it's that bad. With this done, you can finally extend static methods without having to re-declare methods.

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