php - How to prevent sharing of static variables in inherited classes? -
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 children, user.php
, 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
have same $class_name
, $table_name
, makes sense make them static
. actual values assigned when initialize()
method called on child model (e.g. user::initialize();
, product::initialize();
).
problem
i expect end following:
user -> $class_name -> 'user', $table_name -> 'users' product -> $class_name -> 'product', $table_name -> 'products'
yet following:
user -> $class_name -> 'user', $table_name -> 'users' product -> $class_name -> 'user', $table_name -> 'users'
how possible given using late static binding static::
? , how can fixed? goal user
, product
have independent class_name
, table_name
, still keep both variables static
, without redeclaring them on each model, user
, product
or other!
when product::initialize
called, model::$class_name
set "product"
, model::$table_name
"products"
. when user::initialize
called, model::$class_name
, model::$table_name
overwritten "user"
, "users"
.
the static in initialize make difference, if attributes defined in sub classes.
the second part of question answered yourself, either redeclare them or make them non-static.
edit
you use map in combination accessors fake sub-class local inherited static properties (i hope made up).
class foo { private static $class_names = []; private static $table_names = []; public static function getclassname() { return self::$class_names[static::class]; } public static function gettablename() { return self::$table_names[static::class]; } public static function initialize() { self::$class_names[static::class] = static::class; self::$table_names[static::class] = strtolower(static::class).'s'; } } class bar extends foo { } bar::initialize(); class baz extends foo { } baz::initialize(); echo bar::gettablename() . " " . bar::getclassname() . "\n"; echo baz::gettablename() . " " . baz::getclassname() . "\n";
declaring dynamic static properties sadly not work in php 7.
Comments
Post a Comment