search
HomeBackend DevelopmentPHP TutorialDetailed explanation of the usage of PHP anonymous classes

After PHP7, the anonymous class feature was added to PHP. Anonymous classes and anonymous methods make PHP a more modern language and make our code development work more and more convenient. Let's first look at the simple use of anonymous classes.

Recommended: "PHP Video Tutorial"

// 直接定义
$objA = new class

{
    public function getName()
    {
        echo "I'm objA";
    }
};
$objA->getName();

// 方法中返回
function testA()
{
    return new class

    {
        public function getName()
        {
            echo "I'm testA's obj";
        }
    };
}

$objB = testA();
$objB->getName();

// 作为参数
function testB($testBobj)
{
    echo $testBobj->getName();
}
testB(new class{
        public function getName()
    {
            echo "I'm testB's obj";
        }
    });

gives three methods of using anonymous classes at once. Anonymous classes can be directly defined as variables, can be returned using return in methods, or can be passed as parameters to methods. In fact, an anonymous class is like a class that is not defined in advance, but is instantiated directly when it is defined.

// 继承、接口、访问控制等
class A
{
    public $propA = 'A';
    public function getProp()
    {
        echo $this->propA;
    }
}
trait B
{
    public function getName()
    {
        echo 'trait B';
    }
}
interface C
{
    public function show();
}
$p4 = 'b4';
$objC = new class($p4) extends A implements C
{
    use B;
    private $prop1 = 'b1';
    protected $prop2 = 'b2';
    public $prop3 = 'b3';

    public function __construct($prop4)
    {
        echo $prop4;
    }

    public function getProp()
    {
        parent::getProp();
        echo $this->prop1, '===', $this->prop2, '===', $this->prop3, '===', $this->propA;
        $this->getName();
        $this->show();
    }
    public function show()
    {
        echo 'show';
    }
};

$objC->getProp();

Anonymous classes, like ordinary classes, can inherit other classes, implement interfaces, and of course include various access control capabilities. In other words, anonymous classes are no different from ordinary classes in use. But if you use get_class() to get the class name, it will be the class name automatically generated by the system. The name returned by the same anonymous class is of course the same.

// 匿名类的名称是通过引擎赋予的
var_dump(get_class($objC));

// 声明的同一个匿名类,所创建的对象都是这个类的实例
var_dump(get_class(testA()) == get_class(testA()));

So what about static members in anonymous classes? Of course, like ordinary classes, static members belong to the class rather than the instance.

// 静态变量
function testD()
{
    return new class{
        public static $name;
    };
}
$objD1 = testD();
$objD1::$name = 'objD1';

$objD2 = testD();
$objD2::$name = 'objD2';

echo $objD1::$name;

When the static variable in the class is modified, the static variable of all class instances will change accordingly. This is also the characteristic of static members of ordinary classes.

测试代码:
https://github.com/zhangyue0503/dev-blog/blob/master/php/201912/source/PHP%E5%8C%BF%E5%90%8D%E7%B1%BB%E7%9A%84%E7%94%A8%E6%B3%95.php

The above is the detailed content of Detailed explanation of the usage of PHP anonymous classes. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)