Annoying things about PHP

PHP sometimes really annoys me. Some examples from recent experiences:

References and Returning

I often like to return variables from functions by reference. Most of the time, this is just for performance reasons but there are certain places in Geneone where you must use references or the whole thing breaks. One example is the Gene::getObject() function. Two separate functions may want to call methods on this object. If one updates the state of the object, other instances of the object should also be up to date.

To return a reference from a function in PHP you need to do function &funcname() {}. Only variables can be returned as a reference. For example, function &funcname() { return true; } will give an error (certainly on E_ALL on PHP 4.4, I believe this BC break may have been introduced in 4.4.0). In the getObject() function, either a object or a boolean will be returned. If the object exists, a PHP object is returned by the function. If it does not exist, FALSE is returned. And thus whenever you call the function with an invalid object ID, PHP will produce an error because you cannot return a boolean directly by reference.

To get around this, I’ve had to first assign the boolean to a variable and then return the variable. It’s not elegant or tidy, but it does the job. I can’t think of another way to allow a function to return by reference an object or a boolean without a hack such as this.

When upgraded to PHP 4.4.0, I remember having to do quite a bit of hacking to make Wikipedia work with the 4.4.0 BC break. Some PEAR code will produce similar errors to that I’ve just mentioned so there have also been some ugly hacks there.

Optional and Reference

What if you want a function argument to be both optional and sent by reference. The permissions function took two arguments – the permission name and optionally the User object. The idea was that if no user object was provided, the system would use the currently logged in user. Otherwise, the system would check the permissions of the user object provided. Because an object is passed, it also needs to be passed as a reference.

function checkPermission($name, &$user=null) {} doesn’t work. You can’t seem to have an argument which is both optional and passed by reference.


Leave a Reply

Your email address will not be published. Required fields are marked *