Matthew Markus (matthewmarkus) on Posterous http://matthewmarkus.posterous.com Most recent posts at Matthew Markus (matthewmarkus) on Posterous posterous.com Thu, 30 Jul 2009 14:05:00 -0700 PHP: isset(), empty(), etc... http://matthewmarkus.posterous.com/php-isset-empty-etc http://matthewmarkus.posterous.com/php-isset-empty-etc

This is probably of little interest to anyone, but I'm attempting to dump more notes on to the Internet since they then become accessible anywhere. So, without further ado...

I like PHP, but I think that I miss static typing [1]. I always feel that I'm not quite sure what I've got, value wise. Thus, I like to periodically assert() things. Also, checking for values and the existence of variables seems more complicated than it should. Below are some rules of thumb I've come up with in order to preserve my sanity:

$var = func();
if ($var) {...}
// OK since $var is set, $var cast to bool so things like '' == false.

if (isset($_GET['var'])) {...}
// Checks if key exists and value is not NULL.
// isset() acts like a mini try-catch block.

if (isset($this->m_var)) {...}
// Checks if object property exists and is not NULL.
// isset() acts like a mini try-catch block.

if (empty($var->item->title)) {...}
// Same as (! (isset($var->item->title) &&
$var->item->title)).
// empty() acts like a mini try-catch block.

assert('strpos($url, "http://") === 0;');
// Here identity is important since this function also returns false.

[1] http://en.wikipedia.org/wiki/Static_typing#Static_typing

Permalink | Leave a comment  »

]]>
http://posterous.com/images/profile/missing-user-75.png http://posterous.com/users/4aG8WhmtiGbf Matthew Markus matthewmarkus Matthew Markus