Anonymous Class ini berlaku mulai PHP 7, jadi kalau kita masih menggunakan PHP 5 bisa dipastikan belum dapat mencoba Anonymous class. Dari namanya kita memahami sebagai class yang anonim atau tanpa nama. Memang benar bahwa pada anonymous class ini kita tidak menggunakan nama class. Dengan anonymous class ini kita dapat membuat class yang mendadak ada. Misalnya kita membuat method yang bertindak sebagai class.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class 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(); | |
?> |