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

时间:2022-03-31 11:01:09

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?

有没有办法做到这一点?

2 个解决方案

#1


24  

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'=>'user@example.com'));
// username
new User(array('username'=>'John Doe'));
// multiple
new User(array('username'=>'John Doe', 'email'=>'user@example.com'));

#2


1  

This would stop it from running and write out an error based on your config.

这将阻止它运行并根据您的配置写出错误。

class User
{
    function __construct($id,$email,$username) 
    {
       if($id == null && $email == null && $username == null){
            error_log("Required parameter on line ".__LINE__." in file ".__FILE__);
            die();
       }
    }
}

$u = new User();

#1


24  

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'=>'user@example.com'));
// username
new User(array('username'=>'John Doe'));
// multiple
new User(array('username'=>'John Doe', 'email'=>'user@example.com'));

#2


1  

This would stop it from running and write out an error based on your config.

这将阻止它运行并根据您的配置写出错误。

class User
{
    function __construct($id,$email,$username) 
    {
       if($id == null && $email == null && $username == null){
            error_log("Required parameter on line ".__LINE__." in file ".__FILE__);
            die();
       }
    }
}

$u = new User();