Why can't I overload constructors in PHP?

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

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

提交回复
热议问题