Home >Backend Development >PHP Tutorial >PHP delayed static binding
I encountered such a case in a project recently. I feel that all Model classes must be singletons for higher performance. Because all models inherit the unified parent class BaseModel, add the code to control singletons in BaseModel. A simple demonstration is as follows:
Java code
/*基类*/ class BaseModel { private static $instance = null; public static function instance() { if (empty(self::$instance)) { self::$instance = new self(); } return self::$instance; } }
Then each logical subclass Model
Java code
/*商品类*/ class GoodModel extends BaseModel{ public function getInfoById($goodId){ return array( 'id'=>$goodId, 'name'=>'小苹果', 'logo'=>'http://t3.qlogo.cn/mbloghead/65518bb9e5287fcd5864/180' ); } } ################################################################ $good = GoodModel::instance(); var_dump($good);
Such $good is
Java code
object(BaseModel)#1 (0) { }
Unnecessary GoodModel
This is what needs to be introduced self
self::The called variable is only of this class. Even if the class is inherited and the variable is overridden, calling the function in the parent class self::The called variable still outputs the variable value of the parent class and will not output the overwritten value.
So you need to use the static keyword to delay static binding. static represents a subclass
The code is as follows
Java code
/*base class*/
class BaseModel { private static $instance = null; public static function instance() { if (empty(self::$instance)) { self::$instance = new static(); } return self::$instance; } }
The $good at this time is
Java code
object(GoodModel)#1 (0) { }
In fact, you can also use the get_called_class function to solve the above problem. The code is as follows
Java code
class BaseModel { private static $instance = null; public static function instance() { if (empty(self::$instance)) { $className = get_called_class(); self::$instance = new $className(); } return self::$instance; } }