Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call a method from a dynamically instantiated class in PHP?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Call the method from the object

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

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading