PHP中的匿名类
阅读原文时间:2023年07月11日阅读:1

许久不练,要写起来。

hello('PHP'); echo "
"; class TheClass {} interface TheInterface {} trait TheTrait {} $object = new class('A', 'B', 'C') extends TheClass implements TheInterface { use TheTrait; public $A; private $B; protected $C; public function \_\_construct($A, $B, $C) { $this->A = $A; $this->B = $B; $this->C = $C; } }; var\_dump($object); echo "
"; echo get\_class($object); echo "
"; class Outer { private $prop = 1; protected $prop2 = 2; protected function outerFunc1() { return 3; } public function outerFunc2() { return new class($this->prop) extends Outer { private $prop3; public function \_\_construct($prop) { $this->prop3 = $prop; } public function innnerFunc1() { return $this->prop2 + $this->prop3 + $this->outerFunc1(); } }; } } echo (new Outer)->outerFunc2()->innnerFunc1(); echo "
"; echo get\_class(new Outer); ?>

输出:

Hello PHP
object(class@anonymous)#2 (3) { ["A"]=> string(1) "A" ["B":"class@anonymous":private]=> string(1) "B" ["C":protected]=> string(1) "C" }
class@anonymousD:\Test\test.php000000000445025C
6
Outer

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器