The content shared with you in this article is about [php classes and objects] anonymous classes. It has certain reference value. Friends in need can refer to it
Anonymous classes
PHP 7 Start supporting anonymous classes.
Function: Create a one-time simple object
You can pass parameters to the constructor of an anonymous class, you can also extend other classes, implement interfaces, and other common The same traits are used for classes:
<?phpclass SomeClass {}interface SomeInterface {}trait SomeTrait {} var_dump(new class(10) extends SomeClass implements SomeInterface { private $num; public function __construct($num) { $this->num = $num; } use SomeTrait; });/* outputs: object(class@anonymous)#1 (1) { ["Command line code0x104c5b612":"class@anonymous":private]=> int(10) } */
After an anonymous class is nested into a normal Class, it cannot access the private (private), protected (protected) methods or properties of the outer class (Outer class).
In order to access the protected properties or methods of the outer class (Outer class), the anonymous class can extend this outer class.
In order to use the private attribute of the outer class (Outer class), it must be passed in through the constructor:
<?phpclass Outer{ private $prop = 1; protected $prop2 = 2; protected function func1() { return 3; } public function func2() { return new class($this->prop) extends Outer { private $prop3; public function __construct($prop) { $this->prop3 = $prop; } public function func3() { return $this->prop2 + $this->prop3 + $this->func1(); } }; } }echo (new Outer)->func2()->func3(); //6
The same anonymous class declared, the objects created are all instances of this class.
The name of the anonymous class is given by the engine, as shown in the following example. Due to implementation details, this class name should not be relied upon.
<?phpecho get_class(new class {});//class@anonymousD:\phpStudy2018\PHPTutorial\WWW\index.php00500020
Related recommendations:
[php classes and objects] overloading
The above is the detailed content of [php classes and objects] Anonymous classes. For more information, please follow other related articles on the PHP Chinese website!