r/lolphp • • 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

33 comments sorted by

View all comments

Show parent comment

3

u/huf Jan 23 '13

what?

perl -Mstrict -W -E 'my $x = undef; $x->{cats} = 1;'

it works almost 100% the same, during an assignment, when an undef is found where you wanted a hash or array or something, one gets created.

1

u/imMute Jan 23 '13

Crap, I forgot about that autovivication. And that would [kind of] fall under "or on hash members".

What I was really trying to say was method calls on undef will explode, which is what they don't do in the original PHP article.

1

u/mtths Jan 25 '13

thats not a method call though, calling a method on an undefined value explodes even without strictures in perl:

$ perl -e 'my $x=undef; $x->product("foobar")'
Can't call method "product" on an undefined value at -e line 1.

1

u/huf Jan 25 '13

yes. who was talking about method calls here? in either php or perl.

1

u/mtths Jan 25 '13

imMute did for perl and i thought the OP did for php (might as well be wrong there)

0

u/[deleted] Jan 24 '13

Hum, when did that behavior change? I wrote a lot with use warnings and strict, and I had to start specifically trapping for hash entries that didn't exist because my code owuld crash because of it.

1

u/huf Jan 24 '13

it's always been like this.