Multiple Constructors in PHP

In most object-oriented programming languages such as Java, C++ and C#, you can define multiple constructors each having different signatures. The class calls correct constructor based on the number of parameters, and data type of input parameters. In PHP5, however, you can have one and only one constructor. Constructor in PHP is defined with a reserved keyword, __construct(). If the __construct function doesn’t exist, PHP5 will search for the old-style constructor function by the name of the class.

Not being able to define multiple constructors in PHP5 is a big limitation. How do we work around this limitation, and create objects with varying initial values? There are a couple of ways to workaround the problem, and here are the solutions.

1. Use func_get_args() and func_num_args()

class Example {
    function __construct() {
        $argv = func_get_args();
        switch( func_num_args() ) {
            case 1:
                self::__construct1($argv[0]);
                break;
            case 2:
                self::__construct2( $argv[0], $argv[1] );
                break;
            case 3:
                self::__construct2( $argv[0], $argv[1], $argv[2] );
         }
    }

    function __construct1($arg1) {
    ...
    }

    function __construct2($arg1, $arg2) {
    ...
    }

    function __construct3($arg1, $arg2, $arg3) {
    ...
    }
}

$a = new Example("Argument 1");
$b = new Example("Argument 1", "Argument 2");
$b = new Example("Argument 1", "Argument 2", "Argument 3");

2. Use "static" Factory Pattern.

The factory pattern allows for the instantiation of objects at runtime, which may be used to mimic creation of each object with different factory methods. Instead of creating multiple constructors, you can define one factory method for each constructor.

class Example {

    public static function factory1($arg1) {
    }

    public static function factory2($arg1, $arg2) {
    }
}

$a = new Example::factory1("Argument 1");
$b = new Example::factory2("Argument 1", "Argument 2");
Tags: 

Comments

very nice explanation for multiple constructor specially method 1..

By anomyous (not verified)

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.