PHP delays static binding recently encountered such a case in the project, it feels that all Model classes must be single-instance with higher performance. because all models inherit the same parent class BaseModel, you can add the code for controlling the singleton in BaseModel. a simple demonstration is as follows: * base class * classBaseModel {privatestatic $ instancenull; publicst PHP delays static binding
Recently, when we encountered such a case, we felt that all Model classes had to be single-instance with higher performance. because all models inherit the same parent class BaseModel, you can add the code to control the singleton in BaseModel. a simple demonstration is as follows:
/* Base class */class BaseModel {private static $ instance = null; public static function instance () {if (empty (self ::$ instance) {self :: $ instance = new self ();} return self: $ instance ;}}
Then the logic subclass Model
/* Product class */class GoodModel extends BaseModel {public function getInfoById ($ goodId) {return array ('id' => $ goodId, 'name' => 'Apple ', 'logo '=> 'http: // t3.qlogo.cn/mbloghead/65518bb9e5287fcd5864/180 ');}} ######################################## #########################$ good = GoodModel:: instance (); var_dump ($ good );
This class $ good is
object(BaseModel)#1 (0) {}
Non-needed GoodModel
This is self.
Self: The called variable is only for this class. even if the inherited variable of this class is overwritten, the function self in the parent class is called :: the called variable outputs the value of the parent class instead of the overwritten value.
Therefore, you need to use the static keyword to delay static binding. static represents the subclass.
The code is as follows:
/* Base class */class BaseModel {private static $ instance = null; public static function instance () {if (empty (self ::$ instance) {self :: $ instance = new static ();} return self: $ instance ;}}
$ Good is
object(GoodModel)#1 (0) {}
In fact, the get_called_class function can be used to solve the above problem. The code is as follows:
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; }}