PHP Variable Class Shortcut

This is something kinda fun that I just came across, though I haven’t exactly figured out how I want to use it. Essentially it’s creating extremely dynamic variables. I say extreme because it allows you to set the variables name in a variable and the variables class in a variable. It’s a very short script, check it out:

$var_name = 'myClassObject';
$class_name = 'myClass';
${$var_name} = new $class_name();

And now you have a variable you can access as $myClassObject that is an instance of the class ‘myClass’. Pretty cool huh?

However, more useful would probably be just getting a dynamic instance of a class in a function like so:

function instance($class_name)
{
     if (class_exists($class_name))
          return new $class_name();
}

In this example, you would have to store the result in a variable like so:

$myVar = instance('superCoolClass');

One other way you could variate this is to pass by reference the variable you want to store it as.

function instance($class_name, &$var)
{
     if (class_exists($class_name))
          $var = new $class_name();
}

That can be called easily as well.

instance('superCoolClass', $myVar);

I think the previous function makes more sense when reading through code though. Haven’t quite decided how useful a function like this really would be yet. I’ve used dynamic classes in a few situations, but the dynamic variable on top of it hasn’t really come up yet. Still pretty cool the way PHP lets you pull off some things like this.

• Luke Stebner •




---

Comment

 
---