Home > Back-end >  Understanding the anonymous classes
Understanding the anonymous classes

Time:11-23

Hello everyone i am reading a book for advance php i came accross anonymous classe, i don't understand how this work and how to pass data to function i am adding two examples This example is understandable working fine

$object = new class {
 public function hello($message) {
 return "Hello $message";
 }
};
echo$object->hello('PHP');

I need help in this case

The preceding example shows an $object variable storing a reference to an instance of an anonymous class. The more likely usage would be to directly pass the new class to a function parameter, without storing it as a variable, as shown here:

$helper->sayHello(new class {
 public function hello($message) {
 return "Hello $message";
 }
});

I am getting error of undefine variable, can somebody explain to me

CodePudding user response:

You need to extend your code to be able to call this.

$helper must be an instance having the a sayHello() method.

class Helper
{
    public function sayHello($class): void
    {
        echo $class->hello("World");
    }
}

$helper = new Helper();

$helper->sayHello(new class {
    public function hello($message): string
    {
        return "Hello $message";
    }
});

Output

Hello World
  •  Tags:  
  • php
  • Related