Skip to content
Advertisement

What am I doing wrong with my optional PHP arguments?

I have a the following class:

class MyClass {

    public function __construct($id = 0, $humanIdentifier = '') {
        $this->id = $id;
        $this->humanID = $humanIdentifier;
    }
}

So from my interpretation I should be able to pass either $id or $humanIdentifier to that constructor, neither or both if I wanted. However, when I call the code below I am finding that its the $id in the constructor args being set to hello world and not the $humanIdentifier, despite me specifying the $humanIdentifier when calling the constructor. Can anyone see where I am going wrong?

$o = new MyClass($humanIdentifier='hello world');

Advertisement

Answer

Edit: As of PHP8, named arguments are now supported. This wasn’t the case at the time of this post.

PHP does not support named arguments, it will set the value according to the order in which you pass the parameters.

In your case, you’re not passing $humanIdentifier, but the result of the expression $humanIdentifier='hello world', to which $this->id is later set.

The only way I know to mimick named arguments in PHP are arrays. So you could do (in PHP7) :

public function __construct(array $config)
{
    $this->id = $config['id'] ?? 0;
    $this->humanId = $config['humanId'] ?? '';
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement