php new self() 和 new static()的区别

两者都返回实例对象,new self()始终返回同一个实例对象,而 new static()由调用者决定.

<?php
class Person
{

    public function selfInstance()
    {
        return new self();
    }

    public function staticInstance()
    {
        return new static();
    }

}

class P extends Person
{

}

$p1 = new P();
$res1 = get_class($p1->selfInstance());
$res2 = get_class($p1->staticInstance());
var_dump($res1); //Person
var_dump($res2); //P
posted @ 2021-03-11 10:27  HF10  阅读(64)  评论(0)    收藏  举报