Wednesday, November 28, 2007

Learning, the Long Way

Doing something like
print 'This is a test';
is pretty simple, wouldn't you say? Print is a simple command that outputs what its given to the browser. Indeed simple. Now lets look at this:
function foo($data){
echo $data;
${'*'}('This is a test');
This example is a bit more abstract. It does the same thing, but in a different way. First, ${} is called a variable-variable. it allows you to use a string to specify a variable. $name and ${'name'} are the same variable. Valid PHP variables start with an understore or alpha character and then may later have numbers. Here ${'*'} creates a variable $* if you will. This is not a valid variable! Consider the following:
echo $*; //ERROR
echo ${'*'}; // outputs: foo
Ok, so $* is invalid, but how does it work? If a variable-variable defines it, anything flys. Moving on, the second line ${'*'}(); is what is called a variable-function. Basically, it allows you to store the name of a function inside of a variable. Then, by adding () to the variable, it runs the function thats name matches the variable data. If no function is found an error will occour. Consider the following lines which are now technically the same.
${'*'}('Test 1-2-3'); // outputs: Test 1-2-3
foo('Test 1-2-3'); // outputs: Test 1-2-3
The reason we used foo as an echo wrapper is because echo and print are language constructs and not functions. Be sure to play with variable-variables and variable-functions, they are alot of fun and are the next step towards making modular components and classes! This is technically an alternative to:
call_user_func('foo', 'This is a test');

More info here: Variable-variables and Variable-functions

wika wika out

No comments: