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
/*Base class*/
class BaseModel
{
private static $instance = null;
public static function instance()
{
if ( empty(self::$instance)) {
empty (self::$instance)
} }Then Each logical subclass Model
Java code /*Commodity class*/
class GoodModel extends BaseModel{
return array( , > ); } } ######################################### #################### $good = GoodModel::instance(); var_dump($good);
such$good For
Java code object(BaseModel)#1 (0) { }Unnecessary GoodModel
This is the need to introduce self
So the static keyword needs to be used to delay static binding. static represents the subclass
The code is as followsJava code
/*Base class*/
class BaseModel
{
private static $instance = null;
{ Return self::$instance; }
$good at this time is
Java code object(GoodModel)#1 (0) { } In fact, the get_called_class function can also be used to solve the above problem, the code is as followsJava code
class BaseModel
{
private static $instance = null;
public static function instance()
]
off off}
}