Why can't I overload constructors in PHP?

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

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

提交回复
热议问题