Providing PHP Programming Services to Design Professionals

Interested in Electronics?

Check out James' Embedded AVR/Arduino Development, and New Zealand Electronic Component Store

PHP Expression Function Call Precedence

Ok, this one is a bit of a rant.

Today I had some strange failures in a few places in my code, stuff that looked all fine and dandy and hadn't been changed in a very long while stopped working.
Specifically, some array indexes which should have been populated by functions like proc_open and preg_match were no longer being populated.

After some head scratching I realized what was going on, the array I was passing in was either not being passed in by reference, or was being over-written immediately prior to return.

To illustrate, lets look at some code...

function foo(&$bar) { $bar[0] = 'narf'; } $zort = array(); foo($zort); echo $zort[0];

Straight forward enough and any developer should see what it does, first we define zort as an array, pass that to foo which inserts index 0 with value narf, and when we return we echo that value.  No problem with that at all, PHP is happy.

But I do not like that pre-definition of the array (just personal preference), I prefer something like

foo($zort = array());

and I imagine that any developer will look at that and say "no problem, expression arguments are always executed before the function call itself, so this is exactly equivalent to the previous case".



In the almighty wisdom of the team behind PHP, you cannot count on this being true at all. While expressions are evaluated before the function, assignment precedence is undefined
, sometimes it could happen before, sometimes after.  In my particular case it started happening after (I guess after a Debian supplied update of php).  So right before the return value gets, err, returned, $zort is assigned the blank array, completely discarding anything that foo() might have inserted into the array.

You would think this is a fairly obvious design flaw that should be fixed by PHP, I mean, expressions should be evaulated before function calls always, not just some of the time.  But there again you would be wrong, at least according to the PHP developers who have no qualms in closing bug reports on this issue as BOGUS (see for example http://bugs.php.net/bug.php?id=41242&edit=2 - not posted by me but just one of several examples).