Musings of an anonymous geek

October 12, 2005

PHP Object Casting is Cool

Filed under: Scripting,Technology — m0j0 @ 1:18 pm

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!


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at

%d bloggers like this: