Search This Blog

Monday, July 18, 2011

Changes to OO in PHP5

Support for objects in PHP goes all the way back to PHP3. There was never any intention of supporting the idea of classes or objects, but some limited support was added, almost as an afterthought, to provide "syntactic sugar" (to use Zeev Suraski's phrase) for associative arrays. Object support in PHP was originally designed as a convenient way of grouping data and functions, but only a small subset of the features traditionally associated with a full-blown object oriented-programming language was included.

As PHP grew in popularity, the use of an OO approach became increasingly common in large applications. However, the poor internal implementation became limiting. Most notably, there was no support for real encapsulation. You could not specify member variables or methods to be private or protected. Everything was public which, as you've seen, can be problematic.
Additionally, there was no support for abstract interfaces or methods. Methods and member variables could not be declared static. There were no destructors. All of these are concepts that are familiar to anyone with a background in other object-oriented programming languages and the lack of these features in PHP's object model could make that transition from a language like Java (which does support all of these ideas) to PHP difficult.

PHP5 introduces a number of major changes to the object-oriented features in the language that addresses these problems and others, giving PHP real OO capabilities and providing increased performance when using the OO capabilities:
  • Keywords for controlling the visibility of member variables and methods allowing for private, protected, and public members.
  • PHP5 provides dereferencing support such that you can write code such $obj->getObj()->doSomething(). In previous versions of PHP, dereferencing support was limited.
  • Static methods and class constants are now supported, allowing for greater compile-time and runtime checking. Static methods are invoked with the::operator.
  • Unified constructors, using the __construct() method, instead of a method with the same name as the class makes it easier to alter inheritance when multiple classes are involved in a tree of inheritance.
  • Classes in PHP can now have destructors, through the __destruct() method. This allows actions to be taken when the object is destroyed.
  • Support for abstract classes and interfaces has been added. This gives you the capability to define required methods in a parent class while deferring implementation to a subclass. Abstract classes can't be instantiated, only their nonabstract subclasses can.
  • Functions and methods can use type hints on their parameters. It's now possible to specify the class for function parameters that are expecting an object. function foo(Bar $objBar) { ... enables you to be sure that the data type of the parameter $objBar will be an object of class Foo.