PHP new self()和new static()

2019-05-19  本文已影响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() 被谁调用获得谁

上一篇下一篇

猜你喜欢

热点阅读