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.

Resetting Your Password

You can change your password on any enterprise system by following these simple steps:

  1. Login to the password reset page by answering security questions anyone with Google can look up.
  2. Generate a strong password, such as
    yK5*BDbYv91xAaU!BukN
  3. Discover you can’t paste the secure password into the form.
  4. Click your password manager’s “Generate password” icon which generates a password into the field.
  5. Click Save.
  6. Discover that your password manager was blocked from saving the new password and that you no longer know your password.
  7. Discover that you can’t reset your password twice in one day.
  8. Email the system administrator, requesting that your account be unlocked.
  9. Login to the password page again, using those same easily Googable security questions.
  10. Set your password to
    P@$$word123

(Pro-tip: Substituting a dollar sign for each ‘s’ makes it extra secure.)