PHP Object Casting is Cool

I’m from the PHP 3 school of PHP coding. Before that Java was shoved down my throat, and I was happy to be away from project management type stuff and back into Perl and PHP. Doing nothing but procedural coding for a while helped me understand more where an object could really be useful, but I continued to be largely unhappy with how objects worked in PHP — seemed like a lot of overhead, and (in the case of PHP4) a bit of a hacked-up OO implementation in general.

Well, I found one awesome feature that is immediately useful to all PHP web coders, whether you’re pro- or anti- OO: object casting. Sounds hard, but it’s so easy it’s silly. It’s only *technically* OO – in practice, you can use it inline pretty transparently. No declaring, defining, constructing, blah blah blah. Here’s how I’m currently using the feature:

$form = (object)$_POST;

Ta-da! $form would typically be declared in a script that serves as the “action=” to a form. $_POST is an array of stuff that came in from the form. Now, the variables in the $_POST array become attributes of the $form object, and you can refer to them by name without doing anything else. For example, if one of the variables in $_POST was named “test”, you could echo that value to the screen by just doing:

echo $form->test;

Very handy, indeed!
:-)