我的可选PHP参数出错了什么?

mar*_*984 1 php constructor class

我有以下课程:

class MyClass {

    public function __construct($id = 0, $humanIdentifier = '') {
        $this->id = $id;
        $this->humanID = $humanIdentifier;
    }
}
Run Code Online (Sandbox Code Playgroud)

所以根据我的解释,我应该能够将$ id或$ humanIdentifier传递给该构造函数,如果我想要的话,都不能或两者都传递.但是,当我调用下面的代码时,我发现构造函数args中的$ id被设置为hello world而不是$ humanIdentifier,尽管我在调用构造函数时指定了$ humanIdentifier.任何人都可以看到我错在哪里?

$o = new MyClass($humanIdentifier='hello world');
Run Code Online (Sandbox Code Playgroud)

Lou*_*ews 7

PHP不支持命名参数,它将根据传递参数的顺序设置值.

在你的情况,你不及格$humanIdentifier,但表达的结果$humanIdentifier='hello world',到$this->id后面设置.

我知道在PHP中模仿命名参数的唯一方法是数组.所以你可以做(​​在PHP7中):

public function __construct(array $config)
{
    $this->id = $config['id'] ?? 0;
    $this->humanId = $config['humanId'] ?? '';
}
Run Code Online (Sandbox Code Playgroud)