在父类中获取子类的名称(静态上下文) [英] Getting the name of a child class in the parent class (static context)
问题描述
我正在构建一个具有重用和简单性的ORM库;一切都很顺利,除了我被一个愚蠢的继承限制所困扰。请考虑以下代码:
I'm building an ORM library with reuse and simplicity in mind; everything goes fine except that I got stuck by a stupid inheritance limitation. Please consider the code below:
class BaseModel {
/*
* Return an instance of a Model from the database.
*/
static public function get (/* varargs */) {
// 1. Notice we want an instance of User
$class = get_class(parent); // value: bool(false)
$class = get_class(self); // value: bool(false)
$class = get_class(); // value: string(9) "BaseModel"
$class = __CLASS__; // value: string(9) "BaseModel"
// 2. Query the database with id
$row = get_row_from_db_as_array(func_get_args());
// 3. Return the filled instance
$obj = new $class();
$obj->data = $row;
return $obj;
}
}
class User extends BaseModel {
protected $table = 'users';
protected $fields = array('id', 'name');
protected $primary_keys = array('id');
}
class Section extends BaseModel {
// [...]
}
$my_user = User::get(3);
$my_user->name = 'Jean';
$other_user = User::get(24);
$other_user->name = 'Paul';
$my_user->save();
$other_user->save();
$my_section = Section::get('apropos');
$my_section->delete();
显然,这不是我期望的行为(虽然实际行为也有意义)..所以我的问题是,如果你们知道在父类中获得子类名称的意思。
Obviously, this is not the behavior I was expecting (although the actual behavior also makes sense).. So my question is if you guys know of a mean to get, in the parent class, the name of child class.
推荐答案
简而言之。这不可能。在php4中你可以实现一个糟糕的黑客(检查 debug_backtrace()
)但该方法在PHP5中不起作用。参考:
in short. this is not possible. in php4 you could implement a terrible hack (examine the debug_backtrace()
) but that method does not work in PHP5. references:
30423
37684
34421
编辑 :PHP 5.3中后期静态绑定的一个例子(在评论中提到)。请注意,目前的实施存在潜在问题( src )。
edit: an example of late static binding in PHP 5.3 (mentioned in comments). note there are potential problems in it's current implementation (src).
class Base {
public static function whoAmI() {
return get_called_class();
}
}
class User extends Base {}
print Base::whoAmI(); // prints "Base"
print User::whoAmI(); // prints "User"
这篇关于在父类中获取子类的名称(静态上下文)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!