When you’re trying to build more complex classes/applications, the need for doing things dynamically often arises. I figured I’d compile a list of ways to do dynamic PHP for those starting out with PHP. Please note that the list was elaborated with PHP 5 in mind. Some items may work with previous versions, but you’ll have to test it out for that.
Variable Variables
Suppose you need to output a variable but you don’t know in advance which variable it. Take a look at this code:
if ($greet == “hello”)
echo $hello;
else if ($greet == “hey”)
echo $hey;
Using variable variables, you can rewrite the above as follows:
echo $$greet;
Because $greet == “hello”, the end of the script runs as if it were echo $hello. More details on variable variables here.
Dynamic Functions/Objects
The same principle described above can also be applied to functions, member variables, and functions, and object instantiation. Check this out:
// Dynamic member variables, functions, and objects
class TestClass
{
public $testvar = “Property of an object.”;
public function testfunc($text) {
echo $text;
}
}
$dynobj = “TestClass”;
$dynvar = “testvar”;
$dynfunc = “testfunc”;
// Dynamic object instantiation
$obj = new $dynobj();
// Dynamic member variable access
echo $obj->$dynvar;
// Dynamic member function access
$obj->$dynfunc(“Wow, this works!”);
Isn’t that exciting? Gotta love PHP for making it so easy!

