Why can't I overload constructors in PHP?

后端 未结 14 939
长情又很酷
长情又很酷 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 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.

提交回复
热议问题