具有三个可选参数但需要一个参数的 PHP 类构造?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/825658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:58:03  来源:igfitidea点击:

PHP Class construct with three optional parameters but one required?

phpclassparametersconstructoroptional-parameters

提问by farinspace

So basically I understand this ...

所以基本上我明白这一点......

class User
{
    function __construct($id) {}
}

$u = new User(); // PHP would NOT allow this

I want to be able to do a user look up with any of the following parameters, but at least one is required, while keeping the default error handling PHP provides if no parameter is passed ...

我希望能够使用以下任何参数进行用户查找,但至少需要一个参数,同时保持 PHP 提供的默认错误处理(如果没有传递参数)...

class User
{
    function __construct($id=FALSE,$email=FALSE,$username=FALSE) {}
}

$u = new User(); // PHP would allow this

Is there a way to do this?

有没有办法做到这一点?

回答by Gumbo

You could use an array to address a specific parameter:

您可以使用数组来寻址特定参数:

function __construct($param) {
    $id = null;
    $email = null;
    $username = null;
    if (is_int($param)) {
        // numerical ID was given
        $id = $param;
    } elseif (is_array($param)) {
        if (isset($param['id'])) {
            $id = $param['id'];
        }
        if (isset($param['email'])) {
            $email = $param['email'];
        }
        if (isset($param['username'])) {
            $username = $param['username'];
        }
    }
}

And how you can use this:

以及如何使用它:

// ID
new User(12345);
// email
new User(array('email'=>'[email protected]'));
// username
new User(array('username'=>'John Doe'));
// multiple
new User(array('username'=>'John Doe', 'email'=>'[email protected]'));