Tag Archives: php

Dynamic Type Selection in PHP

So, check out this block of PHP code:

class MyClass {
  public function doSomething() {
    echo "Hello there.";
  }
}
$class = "MyClass";
$method = "doSomething";
$instance = new $class();
$instance->$method();

The “new” statement is using a string variable to specify the class being instantiated! What’s more, on the very next line, another string variable is being used, this time to specify the method being invoked.

My background is C-like languages (C, C++, C# and Java), so I was somewhat surprised to discover that this not only executes, but does so without errors. Turns out, this is just how PHP’s new statement works.

In Java, you’d use Class<T> to get the class object, retrieve a specific constructor, and then call the newInstance method, passing any required parameters. So the above example would end up looking something like this:

package myprogram;

import java.lang.Class;
import java.lang.reflect.Method;

class MyClass {
    public MyClass() {}
    public void doSomething() {
        System.out.println("Hello there.");
    }

    public static void main(String[] args) {
        String className = "myprogram.MyClass";
        Class<?> class = Class.forName(className);
        MyClass instance = class.getConstructor().newInstance();

        Method method = class.getMethod("doSomething");
        method.invoke(instance);
    }
}

In a more complex code sample (e.g. passing arbitrary class objects into a method to be instantiated and used in a callback), the Java version has definite advantages in terms of compile time type checking.

But I can’t deny that the simplicity of the PHP version also has some appeal.