Home > Software engineering >  How to call a method from a dynamically instantiated class in PHP?
How to call a method from a dynamically instantiated class in PHP?

Time:05-16

I'm dinamically instantiating a class, but I want to know if there's a way to call a method from this instance, thanks

Code:


if(class_exists($class_name)){
  
  $class = new $class_name;
  $class.method();

}
class foo implements bar {

  public function method(): void {
      echo "method called";
  }

}

Expected Result:

Call the method from the object

Actual Result: Error: Call to undefined function method()

CodePudding user response:

In php use the arrow to call the class's function.

$class.method(); 

should be

$class->method();

alternatively if your method is declared as static you can use it like so

foo::method();
  • Related