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?
Note: PHP lacks support for declaring multiple constructors of different numbers of parameters for a class unlike languages such as Java.
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 (__)!
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".
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.
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]'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With