PHP中的匿名类

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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:\test\test.PHP000000000445025C
6
Outer
@H_404_268@

脚本宝典总结

以上是脚本宝典为你收集整理的PHP中的匿名类全部内容,希望文章能够帮你解决PHP中的匿名类所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。