PHP7之匿名类

匿名类跟匿名函数一样,创建一次性的简单对象

<?php
/**
 * Created by PhpStorm.
 * User: bee
 * Date: 2016/4/24
 * Time: 00:17
 */
echo '匿名函数';
$anonymous_func = function(){return 'function';};
echo $anonymous_func();
echo '<br>';
echo '<hr>';
class common {
    public  $default = 10;
    function __construct($key){
        $this->getVal($key);
    }
    public  function getVal(int $i):int{
        $this->default += $i;
        return $this->default+0.1;
    }
}
echo '有名函数';echo '<br>';
$com = new common(1);

echo $com->getVal(2.2).'--';
echo $com->getVal(2.2).'--';

echo (new common(1))->getVal(8.9);
echo '<hr>';echo '匿名类';
//定义匿名类需继承
echo (new class(1) extends common{})->getVal(90);echo '<br>';
echo (new class(2) extends common{})->getVal(90);

匿名类被嵌套进普通 Class 后,不能访问这个外部类(Outer class)的
private(私有)、protected(受保护)方法或者属性。 为了访问外部类(Outer class)protected
属性或方法,匿名类可以 extend(扩展)此外部类。 为了使用外部类(Outer class)的 private
属性,必须通过构造器传进来:

<?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();//6

匿名函数可以实现闭包,那么相应的匿名类也可以实现闭包

<?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]);

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值