Why can't I overload constructors in PHP?

后端 未结 14 903
长情又很酷
长情又很酷 2020-12-04 11:30

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? Doe

相关标签:
14条回答
  • 2020-12-04 11:59

    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.

    0 讨论(0)
  • 2020-12-04 12:00

    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.

    0 讨论(0)
  • 2020-12-04 12:01

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

    0 讨论(0)
  • 2020-12-04 12:02

    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);
    
    0 讨论(0)
  • 2020-12-04 12:02

    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.

    0 讨论(0)
  • 2020-12-04 12:02
    <?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");
    

    ?>

    0 讨论(0)
提交回复
热议问题