匿名類

匿名類很有用,可以創(chuàng)建一次性的簡單對象。

<?php

// 使用顯性類
class Logger
{
    public function 
log($msg)
    {
        echo 
$msg;
    }
}

$util->setLogger(new Logger());

// 使用匿名類
$util->setLogger(new class {
    public function 
log($msg)
    {
        echo 
$msg;
    }
});

可以傳遞參數(shù)到匿名類的構(gòu)造器,也可以擴(kuò)展(extend)其他類、實(shí)現(xiàn)接口(implement interface),以及像其他普通的類一樣使用 trait:

<?php

class SomeClass {}
interface 
SomeInterface {}
trait 
SomeTrait {}

var_dump(new class(10) extends SomeClass implements SomeInterface {
    private 
$num;

    public function 
__construct($num)
    {
        
$this->num $num;
    }

    use 
SomeTrait;
});

以上例程會(huì)輸出:

object(class@anonymous)#1 (1) {
  ["Command line code0x104c5b612":"class@anonymous":private]=>
  int(10)
}

匿名類被嵌套進(jìn)普通 Class 后,不能訪問這個(gè)外部類(Outer class)的 private(私有)、protected(受保護(hù))方法或者屬性。 為了訪問外部類(Outer class)protected 屬性或方法,匿名類可以 extend(擴(kuò)展)此外部類。 為了使用外部類(Outer class)的 private 屬性,必須通過構(gòu)造器傳進(jìn)來:

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

以上例程會(huì)輸出:

6

聲明的同一個(gè)匿名類,所創(chuàng)建的對象都是這個(gè)類的實(shí)例。

<?php
function anonymous_class()
{
    return new class {};
}

if (
get_class(anonymous_class()) === get_class(anonymous_class())) {
    echo 
'same class';
} else {
    echo 
'different class';
}

以上例程會(huì)輸出:

same class

注意:

注意,匿名類的名稱是通過引擎賦予的,如下例所示。 由于實(shí)現(xiàn)的細(xì)節(jié),不應(yīng)該去依賴這個(gè)類名。

<?php
echo get_class(new class {});

以上例程的輸出類似于:

class@anonymous/in/oNi1A0x7f8636ad2021