Apr 24 2008
Some More PHP Abilities You May Not Know About
Because my first PHP abilities you may not know about post seemed to be useful, here is part 2: some more PHP abilities you may not know about. If you want to learn about ternary operators, calling functions from strings, or variable variables, check out the previous post. Read on to lean about some other things that you can do with PHP.
Modify variable by reference
<?php $test = 'new'; modify($test); echo $test; //prints new variable; function modify(&$variable){ $variable .= ' variable'; } ?>
By using the "&" symbol before the parameter in the function, you pass a reference of the variable to the function.
This saves you from having to say $david = duplicate($david), which can be nice in some situations.
Point a variable to another
This is similar to the example above. You are able to set a variable to reference another by using "=&", an example below:
<?php $david = 'i am david'; $joe =& $david; $joe = 'i am joe'; echo $david; //prints i am joe. ?>
In this example, any change to $joe will result in a change to $david, because $joe is essentially $david.
Default parameter value
I'm amazed at how many people don't know about this. When setting up a function's parameters you are able to specify a default value if the parameter is not passed.
<?php func('test'); function func($foo, $bar = 'value'){ echo $foo . $bar; //we didnt pass $bar, so the result will be 'testvalue' } ?>
The parameter $bar is not passed to the function, so the default value of 'value' is used instead.
Create variable from a string
I explained variable variables in the PHP post previous to this one, but did you know that you can combine two (or more) strings then treat the result as a variable?
<?php $var = 'my'; $bar = 'var'; $myvar = 'testing'; echo ${$var . $bar}; //prints the $myvar variable (testing) ?>
Man, PHP is crazy.

