RSS
 

Archive for April 23rd, 2011

PHP 5.3 Class Friendship Support

23 Apr

One of the useful features of OOP languages like C++ is class friendship via the friend keyword. What this allows you to do is define a class that permits other explicitly named classes to touch its private parts.

For an overly simple example, let’s say you have a User class that carries its user info privately, but you also have a Logger class for writing error and info message to a log. If you tried the following, you’d hit errors telling you that the User properties “id” and “nick” are private:

class User {
  private $id;
  private $nick;
  // ...
}

class Logger {
  // ...
  public static function write($str) {
    $user = User::get_current_user();
    fwrite(self::$handle, "User: {$user->nick} ({$user->id}): {$str}\n");
  }
}

In C++ you could add a simple line to class User like:

friend class Logger;

This would permit the Logger class to access any of its private or protected properties and methods. Despite there being numerous people who demand that you should redesign your code instead of using class friendship, there are many cases where friendship is not only useful but necessary. This is all good and fine except for the fact that the PHP language does not have support for friend classes, nor do its developers have any intention of adding it (the last I heard from the PHP team is they long ago decided against such functionality).

This led me to develop a workaround, which wouldn’t have been possible in the past, but with the flexibility of PHP5.3 and late-static binding, it is now possible. So, without further ado, here’s my implementation of class Friendship.
Read the rest of this entry »

 
No Comments

Posted in PHP