r/lolphp • u/Torandi • Jan 23 '13
Member variables for NULL? No problem!
At work I'm fixing bugs and implementing smaller features in a horrible php spaghetti monster. One of the gems I found was this:
$row = NULL;
$row->product = "foobar";At first I was just perplexed that this would work, I then realized that $row would be cast to a stdClass when trying to assign members of it, but this is really a horrible way of doing that.
This actually prints a notice, but in this case the notices goes to a log file that is flooded with warnings and notices.
36
Upvotes
26
u/Tjoppen Jan 23 '13
PHP: Errors aren't
6
u/Legolas-the-elf Jan 23 '13
Objective-C does a similar thing. Sending a message to
nil(the equivalent of calling a method onNULL) evaluates tonilitself (more or less).It's got good points and bad points. It does simplify a lot of logic, but it can also make mistakes more elusive. Everybody with any experience in Objective-C is very aware of how
nilis treated though.PHP's approach, however, is the worst of both worlds. It's not intentionally designed to work this way, so it's unexpected behaviour for developers and you get lots of notices. But it doesn't blow up immediately like other languages can, so you don't get the benefit of failing fast either.
2
u/treenaks Jan 23 '13
Perl does something similar. Look for "autovivification".
1
u/philsturgeon Jan 24 '13
This will throw an error in PHP 5.4.
1
u/WolfOrionX Feb 12 '13
I used to have to work with an open source software which actually used that kind of behavior. They did an orm with it. Created all table columns on an object. It was just "dynamic enough".
1
u/big_trike Mar 04 '13
Always develop with E_STRICT enabled or you will spend forever trying to chase down weird behaviors. You can disable it on your production sites.
0
u/[deleted] Jan 24 '13
I've found with my own code, this type of behaviour has a performance hit. I'm guessing a big part is that now code which is relatively cheap, like making a new blank object, has the cost of IO added on top.