Home  >  Article  >  Backend Development  >  PHP delayed static binding

PHP delayed static binding

巴扎黑
巴扎黑Original
2016-11-11 17:29:421206browse

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{

public function getInfoById($goodId){

         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

self:: Even if the called variable is only of this class When the inherited variable of this class is overridden and calls the function self:: in the parent class, the called variable still outputs the variable value of the parent class instead of the overwritten value

So the static keyword needs to be used to delay static binding. static represents the subclass

The code is as follows

Java code

/*Base class*/

class BaseModel

{



private static $instance = null;

public static function instance()

 {                                                                    

                                                                                                                                        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 follows

Java code

class BaseModel

{

private static $instance = null;



public static function instance()

                                                                    ]

                                                                                                                                          off   off

    }  

}


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
Previous article:PHP reloadNext article:PHP reload