锟斤拷锟斤拷锟斤拷

PHP 7 锟斤拷始支锟斤拷锟斤拷锟斤拷锟洁。 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷茫锟斤拷锟斤拷源锟斤拷锟揭伙拷锟斤拷缘募虻ザ锟斤拷锟�

<?php

// PHP 7 之前锟侥达拷锟斤拷
class Logger
{
    public function 
log($msg)
    {
        echo 
$msg;
    }
}

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

// 使锟斤拷锟斤拷 PHP 7+ 锟斤拷拇锟斤拷锟�
$util->setLogger(new class {
    public function 
log($msg)
    {
        echo 
$msg;
    }
});

锟斤拷锟皆达拷锟捷诧拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷墓锟斤拷锟斤拷锟斤拷锟揭诧拷锟斤拷锟斤拷锟秸癸拷锟絜xtend锟斤拷锟斤拷锟斤拷锟洁、实锟街接口o拷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;
});

锟斤拷锟斤拷锟斤拷锟教伙拷锟斤拷锟斤拷锟�

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

锟斤拷锟斤拷锟洁被嵌锟阶斤拷锟斤拷通 Class 锟襟,诧拷锟杰凤拷锟斤拷锟斤拷锟斤拷獠匡拷啵∣uter class锟斤拷锟斤拷 private锟斤拷私锟叫o拷锟斤拷protected锟斤拷锟杰憋拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟皆★拷 为锟剿凤拷锟斤拷锟解部锟洁(Outer class锟斤拷protected 锟斤拷锟皆或方凤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟� extend锟斤拷锟斤拷展锟斤拷锟斤拷锟解部锟洁。 为锟斤拷使锟斤拷锟解部锟洁(Outer class锟斤拷锟斤拷 private 锟斤拷锟皆o拷锟斤拷锟斤拷通锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷

<?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
function anonymous_class()
{
    return new class {};
}

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

锟斤拷锟斤拷锟斤拷锟教伙拷锟斤拷锟斤拷锟�

same class

Note:

注锟解,锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟酵拷锟斤拷锟斤拷娓筹拷锟侥o拷锟斤拷锟斤拷锟斤拷锟斤拷示锟斤拷 锟斤拷锟斤拷实锟街碉拷细锟节o拷锟斤拷应锟斤拷去锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟�

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

锟斤拷锟斤拷锟斤拷锟教碉拷锟斤拷锟斤拷锟斤拷锟斤拷冢锟�

class@anonymous/in/oNi1A0x7f8636ad2021