Posted on 2 Comments

Overloading constructors and functions in PHP

PHP Logo

Since I was recently asked whether it’s possible to overload constructors in PHP, or functions in general, here is the quick answer: No, not in the common sense of “overloading”, i.e. creating multiple versions of the same function name with different implementations and arguments. Thus, the following is not possible by default in PHP:

class MyClass {
  /**
   * Default constructor.
   */
  public function __construct() {
    ...
  }

  /**
   * NOT POSSIBLE: Overloaded constructor with additional argument(s).
   */
  public function __construct($someArgument) {
    ...
  }
}

Pattern-based Overloading in PHP

So how is it possible to achieve overloading of constructors and functions in general? Well, we can make use of the factory pattern and add fluent interfaces:

class MyClass {
  /**
   * Hide default constructor.
   */
  private function __construct() {
    ...
  }

  /**
   * Instead of overloaded constructor use factory pattern and fluent interfaces.
   */
  public static function create($someArg) {
    $instance = new self();
    ...
    return $instance; // keep it fluent and return instance
  }
}

func_get_args to the rescue

Ok, but this is not really overloading functions per-se. So, are there any alternatives to this approach? Yes, there are some, e.g. use func_get_args in the default constructor:

public function __construct()  {
   $arguments = func_get_args(); // get variable number of arguments
   ...

But using this approach chances are that you’ll end up with spaghetti code in order to check the arguments specified (amount, type, etc.). Thus, using the factory pattern in combination with fluent interfaces will keep your code clean and easily documentable.

Posted on 4 Comments

Web Interface for SMS Server Tools 3

I have been using SMS Server Tools 3 (smsd) for numerous projects in the past due to its stability and configurability. Since smsd does not provide a graphical UI out-of-the-box I have decided to develop a web interface for users to be able to manage their SMS data, much like an e-mail application, called SMS Server Tools Web Interface. Currently, there is no release available yet. Nevertheless, if you are interested in this project either check back at a later time or subscribe to the github project. Also, please note that at this point I cannot estimate when an initial version will be released.