Page 1 of 1

Initializing as type array

Posted: Wed Jul 11, 2007 10:02 pm
by alex.barylski
I've always initialized members as NULL and then cast their type as appropriate or as required.

I've been running some code through some last minute checks and found that my code was occasionally throwing an error when array_values and similar functions were operating on members which hadn't been initialized (by design - that is they are not intended to be so they are NULL) and because they were set to NULL the error was thrown.

I just tried initializing all my array members as type array()

Code: Select all

$_member = array()
Instead of

Code: Select all

$_member = null;
And that seems to have done the trick and I was able to remove error suppression operators in favor of much cleaner code. :)

How do you deal with these situations? Do you initialize the the expected type or just use error suppression or possible conditionals at the point of error? Is there a better way?

Posted: Wed Jul 11, 2007 10:18 pm
by Benjamin
Forgive me if I misunderstood you, but why would you initialize something as NULL if you need it to be an array?

Posted: Wed Jul 11, 2007 10:56 pm
by feyd
Error suppression is avoided at all costs. Typically initialization uses the type it should be, not an empty type such as null unless it's for an object. Conditionals are used when type hinting isn't possible.

Posted: Wed Jul 11, 2007 11:24 pm
by alex.barylski
astions wrote:Forgive me if I misunderstood you, but why would you initialize something as NULL if you need it to be an array?
Force of habit I guess. I've always initialized as NULL which typically expands to zero (null pointer - cpp). I'm sure I have used the proper type in PHP or Javascript for that matter, but it never occurred to me that errors would be raised if the type was wrong...

I'm not sure why I asked this question even, as now that I've done it, it makes sense to use the type. But like any old habit that dies hard...I guess I needed to hear it from a few others before I officially accepted it as best practice. :)