PHP Lazy Static binding
In a recent project, I have encountered a case in which it is felt that all model classes must be single-case performance. Because all the model inherits the same parent class Basemodel, the code for controlling the singleton is added to the Basemodel, and the following is a simple demonstration:
/* Base class */class basemodel{ private static $instance = null; public static function instance () { if (the Empty (self:: $instance)) {self :: $instance = new self (); } Return self:: $instance; }}
Then the various logical sub-classes model
/* Product class */class Goodmodel extends basemodel{public function Getinfobyid ($goodId) { return array ( ' id ' = $goodId, ' name ' = ' Little Apple ', ' logo ' = ' http://t3.qlogo.cn/mbloghead/65518bb9e5287fcd5864/180 ' ) ; }} ################################################################ $good = Goodmodel::instance (); Var_dump ($good);
This type of $good is
Object (Basemodel) #1 (0) {}
Non-required Goodmodel
This is the need to introduce self
Self:: The variable being called is just the class, even if the class is overridden by an inherited variable to call a function in the parent class self:: The variable that is called or the value of the variable that outputs the parent class and does not output the overridden value
So you need to delay static binding with the static keyword, and static represents the subclass
The code is as follows
/* Base class */class basemodel{ private static $instance = null; public static function instance () { if (the Empty (self:: $instance)) {self :: $instance = new static (); } Return self:: $instance; }}
At this time the $good is
Object (Goodmodel) #1 (0) {}
In fact, the Get_called_class function can also be used to solve the above problem, the code is as follows
Class basemodel{ private static $instance = null; public static function instance () { if (the Empty (self:: $instance)) { $className = Get_called_class (); Self:: $instance = new $className (); } Return self:: $instance; }}