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":"class@anonymous":private]=> string(1) "B" ["C":protected]=> string(1) "C" } 
class@anonymousD:\Test\test.php000000000445025C
6
Outer

 

转载于:https://www.cnblogs.com/aguncn/p/11175858.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值