我需要能够在从基类扩展基类的类中使用静态变量集.
考虑一下:
class Animal {
public static $color = 'black';
public static function get_color()
{
return self::$color;
}
}
class Dog extends Animal {
public static $color = 'brown';
}
echo Animal::get_color(); // prints 'black'
echo Dog::get_color(); // also prints 'black'
Run Code Online (Sandbox Code Playgroud)
这非常适用于PHP 5.3.x(Dog::get_color()打印'brown'),因为它具有后期静态绑定.但我的生产服务器运行PHP 5.2.11,所以我需要调整我的脚本.
有没有一个相当漂亮的解决方法来解决这个问题?
干杯!
克里斯托弗
编辑:目标
如下所述,这是我想要完成的一个非常简化的例子.如果我向你提供了我用来解决问题的两个选项(以及问题本身),有人可能会有一个与我不同的解决方案......
我已经构建了一个基本数据库模型,其中包含"find","find_by"和"find_all"(所有静态)等函数.
在PHP 5.3中有一个函数get_called_class(),我当前用它来确定被调用类的名称,然后使用它来映射正确的数据库表.前课User会指出users.
get_called_class()在PHP 5.2.x中不存在,我发现的hack实现非常不可靠.然后我转向在包含类名的所有模型类中使用静态变量的这个选项.
我在Zend Framework中继承了一些东西时遇到了这个问题.我的决心是,在纯粹的静态土地上,你只有一个选项......在继承类中重新定义函数:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果您能够创建实例 - 您可以使用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'
Run Code Online (Sandbox Code Playgroud)
我想到的唯一另一个选项是使用函数参数来定义一个正在调用它的类的静态函数.它可以默认为__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);
}
}
Run Code Online (Sandbox Code Playgroud)
在PHP 5.3+中,以下是首选:
class Animal {
public static $color = 'black';
public static function get_color()
{
return static::$color; // Here comes Late Static Bindings
}
}
class Dog extends Animal {
public static $color = 'brown';
}
echo Animal::get_color(); // prints 'black'
echo Dog::get_color(); // prints 'brown'
Run Code Online (Sandbox Code Playgroud)