Anonymous classes Create a one-time simple object, just like anonymous functions
/** * Created by Phpstorm. * User:bee * date:2016/4/24 * time:00:17 *
*Echo' anonymous function ';$anonymous _func= function(){return' function ';};Echo$anonymous _func();Echo'
';Echo''; classcommon { Public$default=Ten; function__construct($key){$this->getval ($key); } Public functiongetval(int $i):int{$this-default+=$i;return$this-default+0.1; }}Echo' famous function ';Echo'
';$com=NewCommon1);Echo$com->getval (2.2).'--';Echo$com->getval (2.2).'--';Echo(NewCommon1))->getval (8.9);Echo'';Echo' Anonymous class ';//Define anonymous classes to be inheritedEcho(New class(1) extendscommon{})->getval ( -);Echo'
';Echo(New class(2) extendscommon{})->getval ( -);
After the anonymous class is nested into the normal class, the external class (Outer Class) cannot be accessed
Private, protected (protected) method, or property. In order to access the external class (Outer Class) protected
Properties or methods, anonymous classes can be extend (extended) In addition to the class. In order to use the private of the external class (Outer Class)
property, which must be passed in through the constructor:
!--? php
class
Outer {
private $prop =
1 ;
protected $prop 2 =
2 ;
protected function func1 () {
return
3 ;
public function Func2 () {
return
new
class ($ t His -> prop ) extends Outer {
private $prop 3;
public function __construct ($prop) {$
this ->prop3 = $prop;
public function func3 () {
return $
this -& GT;PROP2 + $
This ->PROP3 + $
this ->func1 (); } }; }}echo (
new Outer)->func2 ()->func3 ();
//6
Anonymous functions can implement closures, then the corresponding anonymous class can also implement closures
/** * Created by Phpstorm. * User:bee * date:2016/4/24 * time:1:51 * *$arr=Array(); for($i=0;$i<3;$i++){$arr[] =New class{ Public$index=0; function__construct() {Echo' Create
'; } Public functiongetval($index){$this->index =$index;Echo$this->index; } Public functiongetindex(){Echo$this->index; } };}$arr[2]->getval (2);Echo'
'; Var_dump ($arr[1]);$arr[1]->getindex ();
'). addclass (' pre-numbering '). Hide (); $ (this). addclass (' has-numbering '). Parent (). append ($numbering); for (i = 1; i <= lines; i++) {$numbering. Append ($ ('
'). Text (i)); }; $numbering. FadeIn (1700); }); });
The above describes the PHP7 anonymous class, including the PHP7 aspects of the content, I hope that the PHP tutorial interested in a friend helpful.