Why can't I overload constructors in PHP?

Viewed 74701

I have abandoned all hope of ever being able to overload my constructors in PHP, so what I'd really like to know is why.

Is there even a reason for it? Does it create inherently bad code? Is it widely accepted language design to not allow it, or are other languages nicer than PHP?

16 Answers

You can't overload ANY method in PHP. If you want to be able to instantiate a PHP object while passing several different combinations of parameters, use the factory pattern with a private constructor.

For example:

public MyClass {
    private function __construct() {
    ...
    }

    public static function makeNewWithParameterA($paramA) {
        $obj = new MyClass(); 
        // other initialization
        return $obj;
    }

    public static function makeNewWithParametersBandC($paramB, $paramC) {
        $obj = new MyClass(); 
        // other initialization
        return $obj;
    }
}

$myObject = MyClass::makeNewWithParameterA("foo");
$anotherObject = MyClass::makeNewWithParametersBandC("bar", 3);

You can use variable arguments to produce the same effect. Without strong typing, it doesn't make much sense to add, given default arguments and all of the other "work arounds."

True overloading is indeed unsupported in PHP. As @Pestilence mentioned, you can use variable arguments. Some people just use an Associative Array of various options to overcome this.

<?php
//php do not automatically call parent class constructor at all if child class has constructor so you have to call parent class constructor explicitly, however parent class constructor is called automatically if child class has no constructor
class MyClass 
{
    function construct1($value1)
    {
        echo "<br/> dummy constructor is called with 1 arguments and it is $value1";
    }
    function construct2($value1,$value2)
    {
        echo "<br/> dummy constructor is called with 2 arguments and it is $value1, $value2";
    }
    function construct3($value1,$value2,$value3)
    {
        echo "<br/> dummy constructor is called with 3 arguments and it is $value1, $value2 , $value3";
    } 
    public function __construct()
    {
        $NoOfArguments = func_num_args(); //return no of arguments passed in function
        $arguments = func_get_args();
        echo "<br/> child constructor is called $NoOfArguments";
        switch ($NoOfArguments) {
            case 1:
                 self::construct1($arguments[0]);
                break;
            case 2:
                self::construct2($arguments[0],$arguments[1]);
                break;

            case 3:
                self::construct3($arguments[0],$arguments[1],$arguments[2]);
                break;

            default:
                echo "Invalid No of arguments passed";
                break;
        }
    }


}
$c = new MyClass();
$c2 = new MyClass("ankit");
$c2 = new MyClass("ankit","Jiya");
$c2 = new MyClass("ankit","Jiya","Kasish");

?>

You can of course overload any function in PHP using __call() and __callStatic() magic methods. It is a little bit tricky, but the implementation can do exactly what your are looking for. Here is the resource on the official PHP.net website:

https://www.php.net/manual/en/language.oop5.overloading.php#object.call

And here is the example which works for both static and non-static methods:

class MethodTest
{
    public function __call($name, $arguments)
    {
        // Note: value of $name is case sensitive.
        echo "Calling object method '$name' "
             . implode(', ', $arguments). "\n";
    }

    /**  As of PHP 5.3.0  */
    public static function __callStatic($name, $arguments)
    {
        // Note: value of $name is case sensitive.
        echo "Calling static method '$name' "
             . implode(', ', $arguments). "\n";
    }
}

$obj = new MethodTest;
$obj->runTest('in object context');

MethodTest::runTest('in static context');  // As of PHP 5.3.0

And you can apply this to constructors by using the following code in the __construct():

$clsName = get_class($this);
$clsName->methodName($args);

Pretty easy. And you may want to implement __clone() to make a clone copy of the class with the method that you called without having the function that you called in every instance...

Adding this answer for completeness with respect to current PHP , since later versions of PHP , you can in fact overload constructors in a way . Following code will help to understand ,

<?php
class A
{
    function __construct()
    {
        $a = func_get_args();
        $i = func_num_args();
        if (method_exists($this,$f='__construct'.$i)) {
            call_user_func_array(array($this,$f),$a);
        }
    }
   
    function __construct1($a1)
    {
        echo('__construct with 1 param called: '.$a1.PHP_EOL);
    }
   
    function __construct2($a1,$a2)
    {
        echo('__construct with 2 params called: '.$a1.','.$a2.PHP_EOL);
    }
   
    function __construct3($a1,$a2,$a3)
    {
        echo('__construct with 3 params called: '.$a1.','.$a2.','.$a3.PHP_EOL);
    }
}
$o = new A('sheep');
$o = new A('sheep','cat');
$o = new A('sheep','cat','dog');
?>

Output :

__construct with 1 param called: sheep
__construct with 2 params called: sheep,cat
__construct with 3 params called: sheep,cat,dog

In this case I recommend using Interfaces:

interface IExample {

    public function someMethod();

}

class oneParamConstructor implements IExample {

    public function __construct(private int $someNumber) {

    }

    public function someMethod(){

    }
}

class twoParamConstructor implements IExample {

    public function __construct(private int $someNumber, string $someString) {

    }

    public function someMethod(){

    }
}

than in your code:

function doSomething(IExample $example) {

    $example->someMethod();

}

$a = new oneParamConstructor(12);
$b = new twoParamConstructor(45, "foo");

doSomething($a)
doSomething($b)

As far as I know, constructor overloading in PHP is not allowed, simply because the developers of PHP did not include that functionality - this is one of the many complaints about PHP.

I've heard of tricks and workarounds, but true overloading in the OOP sense is missing. Maybe in future versions, it will be included.

<?php

    class myClass {

        public $param1 = 'a';
        public $param2 = 'b';

        public function __construct($param1 = NULL, $param2 = NULL) {

            if ($param1 == NULL && $param2 == NULL) {
//                $this->param1 = $param1;
//                $this->param2 = $param2;
            } elseif ($param1 == NULL && $param2 !== NULL) {
//                $this->param1 = $param1;
                $this->param2 = $param2;
            } elseif ($param1 !== NULL && $param2 == NULL) {
                $this->param1 = $param1;
//                $this->param2 = $param2;                
            } else {
                $this->param1 = $param1;
                $this->param2 = $param2;
            }

        }

    }

//    $myObject  = new myClass();
//    $myObject  = new myClass(NULL, 2);
    $myObject  = new myClass(1, '');
//    $myObject  = new myClass(1, 2);

    echo $myObject->param1;
    echo "<br />";
    echo $myObject->param2;

?>
 public function construct1($user , $company)
{
    dd("constructor 1");
    $this->user = $user;
    $this->company = $company;
}

public function construct2($cc_mail , $bcc_mail , $mail_data,$user,$company)
{
    dd('constructor 2');
    $this->mail_data=$mail_data;
    $this->user=$user;
    $this->company=$company;
    $this->cc_mail=$cc_mail;
    $this->bcc_mail=$bcc_mail;
}

public function __construct()
{
    $NoOfArguments = func_num_args(); //return no of arguments passed in function
    $arguments = func_get_args();
    switch ($NoOfArguments) {
        case 1:
             self::construct1($arguments[0]);
            break;
        case 5:
            self::construct2($arguments[0],$arguments[1],$arguments[2],$arguments[3],$arguments[4]);
            break;
        default:
            echo "Invalid No of arguments passed";
            break;
    }

I'm really no OOP expert, but as I understand it overloading means the ability of a method to act differently depending in the parameters it receives as input. This is very much possible with PHP, you just don't declare the input types since PHP does not have strong typing, and all the overloading is done at runtime instead of compile time.

Related