PHP中的匿名类
发布时间:2020-12-13 16:08:05 所属栏目:PHP教程 来源:网络整理
导读:许久不练,要写起来。 ? php // 匿名类,同样可以使用继承,接口,特性//内部匿名类使用外部类的方法和属性,通过继承或构造方法传参 $object = new class { public function hello( $message ) { return "Hello $message " ; }}; echo $object -hello(‘PHP‘ )
许久不练,要写起来。 <?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":"c[email?protected]":private]=> string(1) "B" ["C":protected]=> string(1) "C" } class@anonymousD:Testtest.php000000000445025C 6 Outer (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |