PHP7 anonymous Usage Analysis, php7 anonymous usage

Source: Internet
Author: User

PHP7 anonymous Usage Analysis, php7 anonymous usage

This example describes the usage of the PHP7 Anonymous class. We will share this with you for your reference. The details are as follows:

Like Anonymous functions, an anonymous class creates a one-time simple object.

<? Php/*** Created by PhpStorm. * User: bee * Date: 2016/4/24 * Time: */echo 'Anonymous function'; $ anonymous_func = function () {return 'function';}; echo $ anonymous_func (); echo '<br>'; echo '

Run the following command:

After an anonymous Class is nested in a common class, it cannot access the private (private), protected (protected) methods or attributes of this external Class. To access the attributes or methods of the external class protected, the anonymous class can be extend (extended. To use the private attribute of an external class, it must be passed in through the constructor:

<?phpclass 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

An anonymous function can implement closures, so the corresponding Anonymous class can also implement closures.

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

Run the following command:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.