获取父类中子类的名称(静态上下文) [英] 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 中,您可以实现一个可怕的 hack(检查 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:
edit: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屋!