【问题标题】:PHP Class construct with three optional parameters but one required?具有三个可选参数但需要一个参数的 PHP 类构造?
【发布时间】:2010-10-23 23:07:44
【问题描述】:

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

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

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

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

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

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

有没有办法做到这一点?

【问题讨论】:

  • 您希望如何仅使用 email 参数构造一个 User 实例?为 id 传递 null?

标签: php class parameters constructor optional-parameters


【解决方案1】:

您可以使用数组来处理特定参数:

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'];
        }
    }
}

以及如何使用它:

// 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'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-23
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    • 2020-04-11
    相关资源
    最近更新 更多