PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
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()
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?
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.
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.