You get a bonus - 1 coin for daily activity. Now you have 1 coin

PHP anonymous classes

Lecture



Support for anonymous classes was added in PHP 7. Anonymous classes are very useful when you need to create a simple, one-time object.

<? php

// Before 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;
}
});

They can pass arguments to constructors, extend other classes, implement interfaces, and use treits as a normal class:

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

The result of this example:

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

Embedding an anonymous class in another class does not give it access to private or protected methods and properties of this external class. In order to use the protected properties and methods of the outer class, an anonymous class can extend the outer class. To use the private or protected properties of an external class in an anonymous class, they must be passed through the constructor:

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

The result of this example:

 6

All objects created by the same anonymous class declaration are objects of the same class.

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

if (get_class (anonymous_class ()) === get_class (anonymous_class ())) {
echo 'Same class';
} else {
echo 'Another class';
}

The result of this example:

 Same class

Comment:

Please note that anonymous classes are named by the PHP engine, as shown in the example below. This name should be considered as implementation features and not used in the program logic.

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

The result of running this example will be something like this:

 class @ anonymous / in / ohgfghfghf1 

Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)