温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在PHP7中使用匿名类

发布时间:2021-04-02 17:00:48 来源:亿速云 阅读:129 作者:Leah 栏目:开发技术

今天就跟大家聊聊有关如何在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);

运行效果图如下:

如何在PHP7中使用匿名类

匿名类被嵌套进普通 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]);

运行效果图如下:

如何在PHP7中使用匿名类

看完上述内容,你们对如何在PHP7中使用匿名类有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI