Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 214
farinspace Avatar asked May 05 '09 16:05

farinspace


People also ask

Can PHP class have multiple constructors?

Note: PHP lacks support for declaring multiple constructors of different numbers of parameters for a class unlike languages such as Java.

What is __ construct in PHP?

PHP - The __construct FunctionA constructor allows you to initialize an object's properties upon creation of the object. If you create a __construct() function, PHP will automatically call this function when you create an object from a class. Notice that the construct function starts with two underscores (__)!

What is parent __construct?

We can do this by using the special function call parent::__construct(). The "parent" part means "get the parent of this object, and use it", and the __construct() part means "call the construct function", of course. So the whole line means "get the parent of this object then call its constructor".

Can we override constructor in PHP?

Explanation. In PHP, the only rule to overriding constructors is that there are no rules! Constructors can be overridden with any signature. Their parameters can be changed freely and without consequence.


1 Answers

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]'));
like image 139
Gumbo Avatar answered Oct 16 '22 01:10

Gumbo