What does new self(); mean in PHP?

后端 未结 5 648
别跟我提以往
别跟我提以往 2020-11-30 17:28

I\'ve never seen code like this:

public static function getInstance()
{
    if ( ! isset(self::$_instance)) {
        self::$_instance = new self();
    }
           


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 18:12

    If the class is inherited then calling getInstance() from child will not give you a instance of child. It will only returns an instance of parent instance. This is because we call new self().

    If you want that the child class will return an instance of child class then use new static() in the getInstance() and it will then return the child class instance. This is called late binding!!

提交回复
热议问题