源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

PHP7匿名类用法分析

  • 时间:2021-10-29 13:59 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:PHP7匿名类用法分析
本文实例讲述了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);

运行效果图如下: [img]http://files.jb51.net/file_images/article/201609/2016926153906508.png?2016826153939[/img] 匿名类被嵌套进普通 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]);

运行效果图如下: [img]http://files.jb51.net/file_images/article/201609/2016926154018931.png?2016826154051[/img] 更多关于PHP相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/348.htm]PHP基本语法入门教程[/url]》、《[url=http://www.1sucai.cn/Special/357.htm]PHP运算与运算符用法总结[/url]》、《[url=http://www.1sucai.cn/Special/43.htm]php面向对象程序设计入门教程[/url]》、《[url=http://www.1sucai.cn/Special/495.htm]PHP网络编程技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/623.htm]PHP数组(Array)操作技巧大全[/url]》、《[url=http://www.1sucai.cn/Special/47.htm]php字符串(string)用法总结[/url]》、《[url=http://www.1sucai.cn/Special/84.htm]php+mysql数据库操作入门教程[/url]》及《[url=http://www.1sucai.cn/Special/231.htm]php常见数据库操作技巧汇总[/url]》 希望本文所述对大家PHP程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部