PHP7 anonymous Usage Analysis, php7 anonymous usage
This example describes the usage of the PHP7 Anonymous class. We will share this with you for your reference. The details are as follows:
Like Anonymous functions, an anonymous class creates a one-time simple object.
<? Php/*** Created by PhpStorm. * User: bee * Date: 2016/4/24 * Time: */echo 'Anonymous function'; $ anonymous_func = function () {return 'function';}; echo $ anonymous_func (); echo '<br>'; echo '
Run the following command:
After an anonymous Class is nested in a common class, it cannot access the private (private), protected (protected) methods or attributes of this external Class. To access the attributes or methods of the external class protected, the anonymous class can be extend (extended. To use the private attribute of an external 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
An anonymous function can implement closures, so the corresponding Anonymous class can also implement closures.
<?php/** * Created by PhpStorm. * User: bee * Date: 2016/4/24 * Time: 1:51 */$arr = array();for ($i=0; $i<3; $i++){ $arr[] = new class($i){ public $index=0; function __construct($i) { $this->index = $i; echo 'create</br>'; } public function getVal(){ echo $this->index; } };}$arr[2]->getVal();echo '<br>';var_dump($arr[1]);
Run the following command: