我在Zend框架中对某些内容进行子类化时遇到了这个问题。我的决定是,在完全静止的土地上,你只有一个选择…重新定义继承类中的函数:
class Animal {
public static $color = 'black';
public static function get_color()
{
return self::$color;
}
}
class Dog extends Animal {
public static $color = 'brown';
public static function get_color()
{
return self::$color;
}
}
如果您能够创建实例-您可以使用
get_class($this)
要查找调用类,例如:
class Animal {
public static $color = 'black';
public function getColor() // note, not static
{
$class = get_class($this);
return $class::$color;
}
}
class Dog extends Animal {
public static $color = 'brown';
}
$animal = new Animal();
echo $animal->getColor(); // prints 'black'
$dog = new Dog();
echo $dog->getColor(); // prints 'brown'
我想到的另一个选项是使用静态函数的函数参数来定义从中调用它的类。它可以默认为
__CLASS__
然后你可以
return parent::get_class($class)
从子类。这样的模式可以使重新使用静态函数更容易(因为我怀疑返回公共静态属性是您试图使用的唯一方法
self::
因为在静态方法中:
class Animal {
public static $color = 'black';
public static function get_color($class = __CLASS__)
{
// Super Simple Example Case... I imagine this function to be more complicated
return $class::$color;
}
}
class Dog extends Animal {
public static $color = 'brown';
public static function get_color($class = __CLASS__)
{
return parent::get_color($class);
}
}