Home >Backend Development >PHP Tutorial >PHP delayed static binding

PHP delayed static binding

巴扎黑
巴扎黑Original
2016-11-11 13:13:50950browse

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;  
    }  
}


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn