10

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 ...

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

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

Is there a way to do this?

1
  • How would you want to construct a User instance with just the email parameter? Pass null for id? Commented May 5, 2009 at 16:47

1 Answer 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'=>'[email protected]'));
// username
new User(array('username'=>'John Doe'));
// multiple
new User(array('username'=>'John Doe', 'email'=>'[email protected]'));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.