Reputation: 7923
Can i have a function like this:
public function user_to(String $user = null){
$this->user = $user;
return $this;
}
And another one like this
public function user_to(Array $user = null){
$this->user = $user;
return $this;
}
without having any problem at all? i mean, i want the first to be called only when the parameter is an string and the second one when it is an array.
I know i can do it with only one function and doing a gettype()
to know if its an array or a string but i want to have different functions
Upvotes: 2
Views: 1607
Reputation: 26450
PHP doesn't allow for multiple functions with the same name. So you should instead of defining a separate function with the same name, but different variable-type, you can check for that inside the function.
public function user_to($user = null){
if (is_array($user) || is_string($user)) {
$this->user = $user;
return $this;
} else {
/* Do whatever; for example throw an exception or return false */
}
}
Attempting to redeclare a function that already exists in PHP gives a fatal error. From the manual,
PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.
In the upcoming PHP 8, you can define multiple types in your typehinting, or "union types" (reference).
So you can require the argument to be of either array or string, or nullable (as that is the default value).
public function user_to(array|string|null $user = null) {
$this->user = $user;
return $this;
}
This will however throw a fatal error if you insert a different type, something along the lines of..
Fatal error: Uncaught TypeError: Argument 1 passed to user_to() must be of the type string, object given
Upvotes: 4