Home  >  Article  >  Backend Development  >  What does php anonymous class mean?

What does php anonymous class mean?

WBOY
WBOYOriginal
2022-03-25 10:30:532445browse

In PHP, an anonymous class refers to a class without a name. Anonymous classes cannot be referenced. You can use "new class" to create an anonymous class. The syntax is "new class(parameter 1, parameter 2, . ..){Member properties and methods;};"; An anonymous class can only create an object once.

What does php anonymous class mean?

The operating environment of this article: Windows 10 system, PHP version 7.1, Dell G3 computer.

What does php anonymous class mean

Anonymous classes refer to classes without names and they cannot be referenced. Because anonymous classes have no names, an anonymous class can only create an object once.

You can create an anonymous class through new class, which is similar to the definition of an ordinary class. The difference is that there is no need to set a class name, as shown below:

new class(参数1, 参数2, ...){
    成员属性和方法;
};

Let’s look at a simple An example is as follows:

<?php
    $name = new class(&#39;中文网&#39;){
        private $name;
        public function __construct($name){
            $this->name = $name;
        }
        public function output(){
            echo $this->name;
        }
    };
    $name->output();
?>

Anonymous classes can be declared in an internal method of a class or directly assigned to variables. When an anonymous class is nested into a normal class, methods or properties modified with private or protected in the external class cannot be accessed. If you want to access properties or methods modified by protected in an external class, you can use an anonymous class to inherit this external class. If you want to use private-modified properties of an external class, you must pass them in through the constructor.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of What does php anonymous class mean?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn