Search the blog

Sometimes you need to create ojects from classes and then call their functions dynamically. You may, for example, have objects stored in a JSON file complete with parameters (such as the object graph of a dependency injection container). How do you go about creating the object and call the functions using parameters?

eval() would do it but you need to be extremely cautious when using this — and avoid it if possible due to the havoc it can wreak if used incorrectly.

Instead, we can use PHP’s ReflectionClass. In OOP, reflection allows you to do things with objects at runtime (as opposed to during compilation or interpretation) such as programmatically load a class and call its functions.

Here is an example; the comments should make it self-explanatory.


// A class to test with
class Foo {
    private $message1;
    public function __construct($message1) {
       $this->message1 = $message1; 
    public function doSomething ($message2) {
        echo $this->message1 . ', ' . $message2;   

// Class name and function name as string
$class        = 'Foo';
$function     = 'doSomething';

// Create the Reflection class
$reflection   = new ReflectionClass('Foo');

// Create the Foo object by passing an array of parameters (just one in this example)
$obj          = $reflection->newInstanceArgs(['message 1']);

// Call the function using parameters as you would a normal function
$obj->$function('message 2'); // Outputs 'message 1, message 2'

Tim Bennett is a Leeds-based web designer from Yorkshire. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.