美文网首页
PHP new self()和new static()

PHP new self()和new static()

作者: 长安猎人 | 来源:发表于2019-05-19 18:07 被阅读0次
<?php

class Father
{
    public function getNewFather()
    {
        return new self();
    }

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

class Sun1 extends Father
{

}

class Sun2 extends Father
{

}

$sun1 = new Sun1();
$sun2 = new Sun2();

print get_class($sun1->getNewCaller()) . PHP_EOL;
print get_class($sun1->getNewFather()) . PHP_EOL;
print get_class($sun2->getNewCaller()) . PHP_EOL;
print get_class($sun2->getNewFather()) . PHP_EOL;

运行结果

D:\App\php-7.2.18\php.exe F:\www\php-project\php-inner\test.php
Sun1
Father
Sun2
Father

Process finished with exit code 0

结论:
1.new self() 无论何时都能获得自己
2.new static() 被谁调用获得谁

相关文章

网友评论

      本文标题:PHP new self()和new static()

      本文链接:https://www.haomeiwen.com/subject/ynmqzqtx.html