9

だから基本的に私はこれを理解しています...

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

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

次のパラメーターのいずれかを使用してユーザー検索を実行できるようにしたいのですが、パラメーターが渡されない場合に PHP が提供するデフォルトのエラー処理を維持しながら、少なくとも 1 つが必要です ...

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

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

これを行う方法はありますか?

4

1 に答える 1

24

配列を使用して、特定のパラメーターをアドレス指定できます。

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'));
于 2009-05-05T16:16:39.420 に答える