Consider Model.php
:
class Model {
protected static $class_name;
protected static $table_name;
protected $id;
public static function initialize() {
static::$class_name = get_called_class();
static::$table_name = strtolower(static::$class_name).'s';
}
}
and its children, User.php
and Product.php
:
class User extends Model {
protected $username;
protected $password;
}
User::initialize();
class Product extends Model {
protected $name;
protected $price;
}
Product::initialize();
Since every User
or Product
will have the same $class_name
and $table_name
, it makes sense to make them static
. The actual values are assigned when initialize()
method is called on the child model (e.g. User::initialize();
and Product::initialize();
).
Problem
I would expect to end up with the following:
User -> $class_name -> 'User', $table_name -> 'users'
Product -> $class_name -> 'Product', $table_name -> 'products'
Yet I get the following:
User -> $class_name -> 'User', $table_name -> 'users'
Product -> $class_name -> 'User', $table_name -> 'users'
How is this possible given that I am using late static binding with static::
? And how can this be fixed? My goal is for User
and Product
to have independent class_name
and table_name
, but still keep both variables static
, hopefully without redeclaring them on each model, be it User
, Product
or any other!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…