许久不练,要写起来。
<?php //匿名类, 同样可以使用继承,接口,特性 //内部匿名类使用外部类的方法和属性,通过继承或构造方法传参 $object = new class { public function hello($message) { return "Hello $message"; } }; echo $object->hello('PHP'); echo "<br/>"; 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 "<br/>"; echo get_class($object); echo "<br/>"; 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 "<br/>"; 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