首頁  >  文章  >  後端開發  >  PHP7匿名類別的用法範例(程式碼)

PHP7匿名類別的用法範例(程式碼)

不言
不言轉載
2019-02-12 14:07:281709瀏覽

這篇文章帶給大家的內容是關於PHP7匿名類別的用法範例(程式碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

<?php
/**
 * Created by PhpStorm.
 * User: Itboot
 * Date: 2019/1/17
 * Time: 18:15
 */

class An
{
    private $num;
    protected $age = 15;
    public function __construct() {
        $this->num = 1;
    }
    protected function bar(): int {
        return 10;
    }

    public function drive() {
        return new class($this->num) extends An{
            protected $id;

            public function __construct($num) {
                $this->id = $num;
            }
            public function ea() {
                return $this->id + $this->age + $this->bar();
            }
        };
    }
}
echo (new An())->drive()->ea();
<?php
$fun = function (){
    print &#39;这是匿名函数&#39;. PHP_EOL;
};
$fun();
===================================================================================================================
class Animal
{
    public $num;
    public function __construct(...$args)
    {
        $this->num = $args[0];
    }

    public function getValue($su): int
    {
        return $this->num + $su;
    }
}

$an = new Animal(4);
echo $an->getValue(12) . PHP_EOL;
echo &#39;匿名类&#39;. PHP_EOL;
echo (new class(11) extends Animal{})->getValue(12);

以上是PHP7匿名類別的用法範例(程式碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除