15 June 2006
Differences between PHP4 and 5’s Object Model
Listen to any OOP-fanatic for more than 5-minutes talk about the difference between PHP4 and 5 and you’ll hear them carry on about the vast improvements to PHP’s object model. But what are those changes, exactly? There are only three I’ve ever heard promoted: destructors, tostring(), and objects getting passed by reference by default.
There are other differences that I’ve found only when adapting code written in PHP5 back to PHP4. One is about references. Given this chunk of code,
$form = Form::Unserialize();
foreach (get_object_vars ($form) as $property => $value) {
$value->update();
}
It works as intended in PHP5. And it runs without errors in PHP4. But it doesn’t work as intended in PHP4. In PHP4, $value is a clone of the actual variable. In PHP5, it’s a reference. In either case, the update() method exists. But in PHP4, its called on the cloned object that falls out of scope almost immediatly. In PHP5, its called on the object the reference refers to, specifically, the original variable in the $form object. So the code that is PHP4-compatible (but still works in PHP5) is:
$form = Form::Unserialize();
foreach (get_object_vars ($form) as $property => $value) {
$value->update(); // updates value, cloned or otherwise
$form->$property = $value; // sets the original variable to value,
// whether cloned or otherwise
}
Another difference is the get_class function. get_class returns the type of the object as a string. In PHP4, it is returned in lowercase. In PHP5, it’s in the unaltered case of the original. Since PHP classes and functions AREN’T case sensitive, but variables (and comparisons) ARE, any classes that aren’t lowercase-named aren’t intristically compatible across PHP4 and 5 if they depend on this function. So you need a compatibility-bridge, like
function get_class_lowercase ($object) {
return strtolower (get_class ($object));
}
Use that in place of get_class and you’ve got compatibility.

