Development #php#programming 2 min

PHP4 vs PHP5

Translation of the original in Catalan. Read it in: CatalàCastellano

While reading the PHP|Architect's Guide to PHP Design Patterns (isbn: 0973589825) I found a couple of days ago a small list of what the fundamental differences between PHP4 and PHP5 were, apart from the cliché that with the Zend 2.1 engine we now have OOP support and that everyone tells me the object model PHP5 uses is still very bad; well, with this we'll be able to see just how bad it is.

  • Object handles
  • Better constructors (uniform name, changing $this not allowed)
  • Destructors now exist
  • Visibility (public, protected, private for methods and attributes)
  • Exceptions (an alternative to triggering errors using the new try{} catch{} syntax)
  • Class constants (defined using the class as a name space)
  • Reflection (dynamic examination of classes, methods and arguments)
  • Type hinting (specifying expected classes or interfaces for method arguments)

We can also find other somewhat less known new features:

  • New magic methods (__get() and __set() allow you to control attribute access; __call() lets you dynamically intercept all method calls to the object; __sleep() and __wakeup() let you override serialization behavior; and __toString() lets you control how an object represents itself when cast as a string)
  • Autoloading (allows the end user to try to automatically load the class the first time a reference to it is made)
  • Final (do not allow a method or a class to be overridden by subclasses)

On top of that there are things like the object handles part, which have a lot to offer:

  • Create an object by reference, as in $obj =& new Class;
  • Pass an object by reference, like function funct(&$obj_param) {}
  • Catch an object by reference function &some_funct() {} $returned_obj =& some_funct()

Essentially, what I liked most is summarized here, I know it's in English but I was staggeringly lazy about translating it. If I feel like it one of these days I'll give more details on how to take advantage of these features to implement design patterns with PHP5. You really start to feel like a real programmer when you see that PHP5 has no problem at all supporting structures that until now were so far out of its reach.