>  기사  >  백엔드 개발  >  PHP에서 new self()와 new static()의 차이점

PHP에서 new self()와 new static()의 차이점

coldplay.xixi
coldplay.xixi앞으로
2020-06-08 10:01:372544검색

PHP에서 new self()와 new static()의 차이점

PHP에서 new self()와 new static()의 차이점

new static()은 php5.3 버전에 도입된 새로운 기능입니다.

new static과 new self()는 모두 새로운 기능입니다. Object

코드를 직접 보세요

class Father
{
    public function getNewFather()
    {
        return new self();
    }
  
    public function getNewCaller()
    {
        return new static();
    }
}
  
$f = new Father();
  
var_dump(get_class($f->getNewFather())); // Father
var_dump(get_class($f->getNewCaller())); // Father

getNewFather와 getNewCaller는 모두 Father 실제 열을 반환하고 있습니다

여기서는 new self()나 new static() 사이에 차이가 없는 것 같습니다

그럼 아래 예를 보세요

class Sun1 extends Father{
  
}
  
$sun1 = new Sun1();
  
var_dump($sun1->getNewFather()); // object(Father)#4 (0) { }
var_dump($sun1->getNewCaller()); // object(Sun1)#4 (0) { }

getNewFather 반환은 Father의 실제 열이고,

getNewCaller는 호출자의 실제 열을 반환합니다.

그 차이는 상속에만 반영될 수 있으며, 상속이 없으면 두

새 자체 사이에는 차이가 없습니다. () 반환 실제 열은 변경되지 않습니다. 누가 호출하든 클래스의 실제 열이 반환됩니다.

새로운 정적은 호출자에 의해 결정됩니다.

추천 튜토리얼: "PHP 비디오 튜토리얼"

위 내용은 PHP에서 new self()와 new static()의 차이점의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 liqingbo.cn에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제