Overloading constructors and functions in PHP

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.

You may also like...

1 Response

  1. guest says:

    Another one using heritage:

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

    }
    }

    class MySecondClass extends MyClass {

    public function __construct($someArgument = null) { // Argument must be optional to avoid String Standards warning
    if (!$someArgument) {
    return parent::__construct();
    }
    // Do something with $someArgument …
    }
    }

    $a = new MySecondClass();
    $b = new MySecondClass($someArgument);

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.