PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 16, 2022

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

 May 16, 2022     class, instance, methods, oop, php     No comments   

Issue

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


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


Answered By - DAG
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing