Can you overload constructors in php?

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?

asked Jan 30, 2010 at 21:12

2

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);

answered Feb 1, 2010 at 7:15

Alex WeinsteinAlex Weinstein

9,7558 gold badges43 silver badges59 bronze badges

5

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."

answered Jan 30, 2010 at 21:27

pestilence669pestilence669

5,6081 gold badge22 silver badges34 bronze badges

1

For completeness, I'll suggest Fluent Interfaces. The idea is that by adding return $this; to the end of your methods you can chain calls together. So instead of

$car1 = new Car('blue', 'RWD');
$car2 = new Car('Ford', '300hp');

(which simply wouldn't work), you can do:

$car = (new Car)
       ->setColor('blue')
       ->setMake('Ford')
       ->setDrive('FWD');

That way you can pick exactly which properties you want to set. In a lot of ways it's similar to passing in an array of options to your initial call:

$car = new Car(['make' => 'Ford', 'seats' => 5]);

answered Jun 28, 2016 at 13:46

Can you overload constructors in php?

CodemonkeyCodemonkey

4,2024 gold badges38 silver badges72 bronze badges

5

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.

answered Jan 30, 2010 at 21:30

Dominic BarnesDominic Barnes

27.7k8 gold badges63 silver badges89 bronze badges

PHP Manual: Function Arguments, Default Values

I have overcome this simply by using default values for function parameters. In __constuct, list the required parameters first. List the optional parameters after that in the general form $param = null.

class User
{
    private $db;
    private $userInput;

    public function __construct(Database $db, array $userInput = null)
    {
        $this->db = $db;
        $this->userInput = $userInput;
    }
}

This can be instantiated as:

$user = new User($db)

or

$user = new User($db, $inputArray);

This is not a perfect solution, but I have made this work by separating parameters into absolutely mandatory parameters no matter when the object is constructed, and, as a group, optional parameters listed in order of importance.

It works.

answered Feb 13, 2017 at 19:00

Can you overload constructors in php?

Anthony RutledgeAnthony Rutledge

6,2341 gold badge36 silver badges43 bronze badges

they say this work:


and, it seem every one are happy with it, but for me it didn't work... if you get it to work, its one kind of overloading too...

it take all argoments and pass them to the secondary function constructor...

answered Dec 26, 2012 at 12:38

Can you overload constructors in php?

Hassan FaghihiHassan Faghihi

1,7361 gold badge38 silver badges51 bronze badges

3

 dummy constructor is called with 1 arguments and it is $value1";
    }
    function construct2($value1,$value2)
    {
        echo "
dummy constructor is called with 2 arguments and it is $value1, $value2"; } function construct3($value1,$value2,$value3) { echo "
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 "
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");

?>

answered Oct 19, 2017 at 11:14

You can use conditional statements in your constructor and then perform your task. Eg.

  class Example
  {
      function __construct($no_of_args)

      {// lets assume 2
          switch($no_of_args)
          {
              case 1:
                // write your code
              break;
              case 2:
                //write your 2nd set of code
              break;
              default:
           //write your default statement
         }
      }
   }

    $object1 = new Example(1);  // this will run your 1st case
    $object2 = new Example(2);  // this will run your 2nd case

and so on...

jonsca

10k26 gold badges54 silver badges61 bronze badges

answered Dec 2, 2012 at 8:22

DrGeneralDrGeneral

1,42914 silver badges21 bronze badges

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 ,


Output :

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

answered Sep 9, 2020 at 17:10

parth_07parth_07

1,24216 silver badges20 bronze badges

1

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)

answered Feb 7 at 8:08

Can you overload constructors in php?

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.

answered Jan 30, 2010 at 21:20

Can you overload constructors in php?

Charlie SaltsCharlie Salts

12.8k7 gold badges47 silver badges77 bronze badges

I think we can also use constructor with default arguments as a potential substitute to constructor overloading in PHP.

Still, it is really sad that true constructor overloading is not supported in PHP.

answered Mar 18, 2013 at 5:23

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 "
"; echo $myObject->param2; ?>

answered Aug 18, 2018 at 12:50

Can you overload constructors in php?

anteloveantelove

2,76420 silver badges19 bronze badges

 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;
    }

answered Dec 14, 2020 at 11:23

Can you overload constructors in php?

Ali RazaAli Raza

5844 silver badges13 bronze badges

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.

answered Jan 30, 2010 at 22:59

Matteo RivaMatteo Riva

24.3k12 gold badges71 silver badges104 bronze badges

1

Is it possible to overload the constructor?

Constructors can be overloaded in a similar way as function overloading. Overloaded constructors have the same name (name of the class) but the different number of arguments.

Is overloading possible in PHP?

PHP does not support method overloading. In case you've never heard of method overloading, it means that the language can pick a method based on which parameters you're using to call it. This is possible in many other programming languages like Java, C++.

Does PHP support constructor?

PHP allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.

Can we have two constructors in a class PHP?

A class can have multiple constructors that differ in the number and/or type of their parameters. It's not, however, possible to have two constructors with the exact same parameters.