Archive for the 'PHP' Category
Dynamic PHP
Tuesday, December 12th, 2006

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:

Using variable variables, you can rewrite the above as follows:

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:

Isn’t that exciting? Gotta love PHP for making it so easy!