PHP Class construct with three optional parameters but one required


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?

Best Solution

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'=>''));
// username
new User(array('username'=>'John Doe'));
// multiple
new User(array('username'=>'John Doe', 'email'=>''));
Related Question