<?php
class Person
{
public function __construct()
{
echo "Person 构造方法\n";
}
public function createObject_1()
{
echo "创建对象: Person_1\n";
return new self();//new self()创建的永远是Person对象,无论是不是子类调用还是当前类调用
}
public function createObject_2()
{
echo "创建对象: Person_2\n";
return new static();//new static()如果子类调用,就创建子类对应的对象
}
}
class Father extends Person
{
public function __construct()
{
echo "Father 构造方法\n";
}
}
$f = new Father();
$new = $f->createObject_1();
// var_dump($f->createObject_1());
var_dump($new instanceof Father);//false
var_dump($new instanceof Person);//true
echo "***********************************\n";
$other = $f->createObject_2();
var_dump($other instanceof Father);//true
var_dump($other instanceof Person);//true
PHP中的new self() VS new static()区别
于 2022-09-28 14:20:17 首次发布