这个消息在php 5.4中显示了一些奇怪的原因.
我的班级看起来像这样:
abstract class model{
private static
$tableStruct = array();
abstract protected static function tableStruct();
public static function foo(){
if(!isset(self::$tableStruct[get_called_class()]))
self::$tableStruct[get_called_class()] = static::tableStruct();
// I'm using it here!!
}
}
Run Code Online (Sandbox Code Playgroud)
并应使用如下:
class page extends model{
protected static function tableStruct(){
return array(
'id' => ...
'title' => ...
);
}
...
}
Run Code Online (Sandbox Code Playgroud)
为什么制作子类所需的静态方法被认为是违反标准的?
抽象静态方法是一种奇怪的概念.静态方法基本上将"硬编码"到类的方法,确保只有一个实例(~singleton).但是将它抽象化意味着你想强制其他一些类来实现它.
我看到你正在尝试做什么,但在处理抽象类时,我会避免在基类中使用静态方法.你可以做的是使用后期静态绑定(static::)来调用"child"类中的tableStruct方法.这并不强制该方法像abstract一样实现,但是你可以测试实现并抛出异常(如果它不存在).
public static function foo(){
// call the method in the child class
$x = static::tableStruct();
}
Run Code Online (Sandbox Code Playgroud)