我正在构建一个 ORM 库,考虑到重用性和简单性;一切都很顺利,除了我被一个愚蠢的继承限制所困扰。请考虑下面的代码:
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();
显然,这不是我所期望的行为(尽管实际行为也是有道理的)。所以我的问题是你们是否知道在父类中获取子类名称的方法。
如果您能够想出一种在静态上下文之外执行此操作的方法,则无需等待 PHP 5.3。在 php 5.2.9 中,在父类的非静态方法中,您可以执行以下操作:
get_class($this);
它将以字符串形式返回子类的名称。
i.e.
class Parent() {
function __construct() {
echo 'Parent class: ' . get_class() . "\n" . 'Child class: ' . get_class($this);
}
}
class Child() {
function __construct() {
parent::construct();
}
}
$x = new Child();
这将输出:
Parent class: Parent
Child class: Child
甜蜜吧?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)