views:

1511

answers:

2

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?

+5  A: 

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]'));
Gumbo
A: 

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();
Chris Bartow
That wouldn't get to the if statement inside, $u = new User() will fail because you didn't provide parameters that have no defaults.
seanmonstar