时间:2021-07-01 10:21:17 帮助过:33人阅读
匿名类跟匿名函数一样,创建一次性的简单对象
/**
 * Created by PhpStorm.
 * User: bee
 * Date: 2016/4/24
 * Time: 00:17
 */echo'匿名函数';
$anonymous_func = function(){return'function';};
echo$anonymous_func();
echo'
';
echo'
';
classcommon {public$default = 10;
    function__construct($key){$this->getVal($key);
    }
    publicfunctiongetVal(int $i):int{$this->default += $i;
        return$this->default+0.1;
    }
}
echo'有名函数';echo'
';
$com = new common(1);
echo$com->getVal(2.2).'--';
echo$com->getVal(2.2).'--';
echo (new common(1))->getVal(8.9);
echo'
';echo'匿名类';
//定义匿名类需继承echo (newclass(1) extendscommon{})->getVal(90);echo'
';
echo (newclass(2) extendscommon{})->getVal(90);
匿名类被嵌套进普通 Class 后,不能访问这个外部类(Outer class)的
private(私有)、protected(受保护)方法或者属性。 为了访问外部类(Outer class)protected
属性或方法,匿名类可以 extend(扩展)此外部类。 为了使用外部类(Outer class)的 private
属性,必须通过构造器传进来:
classOuter
{private $prop = 1;
    protected $prop2 = 2;
    protected function func1()
    {
        return3;
    }
    public function func2()
    {
        returnnewclass($this->prop) extendsOuter {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匿名函数可以实现闭包,那么相应的匿名类也可以实现闭包
/**
 * Created by PhpStorm.
 * User: bee
 * Date: 2016/4/24
 * Time: 1:51
 */$arr = array();
for ($i=0; $i<3; $i++){
    $arr[] = newclass{public$index=0;
        function__construct()
        {echo'create';
        }
        publicfunctiongetVal($index){$this->index = $index;
            echo$this->index;
        }
        publicfunctiongetIndex(){echo$this->index;
        }
    };
}
$arr[2]->getVal(2);
echo'
';
var_dump($arr[1]);
$arr[1]->getIndex();

以上就介绍了PHP7之匿名类,包括了php7方面的内容,希望对PHP教程有兴趣的朋友有所帮助。