Why can't I overload constructors in PHP?

2019-01-16 07:05发布

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?

12条回答
Anthone
2楼-- · 2019-01-16 07:26

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.

查看更多
霸刀☆藐视天下
3楼-- · 2019-01-16 07:26
<?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");

?>

查看更多
唯我独甜
4楼-- · 2019-01-16 07:28

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.

查看更多
beautiful°
5楼-- · 2019-01-16 07:29

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]);
查看更多
太酷不给撩
6楼-- · 2019-01-16 07:30

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.

查看更多
Root(大扎)
7楼-- · 2019-01-16 07:33

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.

查看更多
登录 后发表回答