Tuesday, March 24, 2009

Been working with PHP to build a small scale website - it's a refreshing change from ASP.net, and so happens to be the first programming language I ever learnt. Pretty interesting - given how I've been weaned to programming by Java, the differences between PHP and Java makes it an interesting experience (I'm repeating myself).

PHP is very strict on case-sensitivity, so.
Java is pretty strict as it is - classnames, methodnames, variables must be in the same case. PHP goes one up - array keys are also case sensitive. Coupled with the fact that I was working with a MySQL database (which is not case-sensitive at all) made for a frustrating bug-tracking session. (Live and learn eh?)

But the most interesting thing I stumbled upon is (*drumroll*) variable functions.
This is perfectly legal PHP -
function foo($string)
{
    print($string);
}
$func = "foo";
$func("bar");
?>
and it outputs "bar".

Essentially, you can put a function name as a string, and execute it by calling the variable and parenthesis. (It doesn't work with language constructs like echo or print, which is why $func = "echo";$func("bar"); doesn't work).

Now that could prove very very VERY useful. How so?
Imagine that you have to sanitize input, and you have three methods to do so, checkInt,checkStr and checkBool.

Normally you would call it as such :
if($type == "Str")
checkStr($str);
elseif($type == "Int")
checkInt($str);
else
checkBool($str);

Now, variable declarations allow you to do this :
$method = "check".$type;
$method($str);

See how much easier it is? (I haven't tested the above code, but I'm pretty sure it'll work).

Variable functions are really really interesting :D

No comments: