'Laravel function that can handle a request or strings
I have a function:
public static function linkClient(Request $request){
//do things
}
This function is called by 2 different things. 1 is a post request with post data. In that case, this works fine:
public static function linkClient(Request $request){
$data = $request->all();
// do things with data
}
The second call to this function passes 2 strings. how can i make it so this function can handle either the Request or the strings?
In laymen's terms I would write:
public static function linkClient(Request $request or $string1,$string2){
if ($request){
$data = $request->all();
//do things to request
}
if($string1 or $string2){
//do string things
}
}
Solution 1:[1]
What you are looking for is function overloading, which php does not support. You can try to hack it together using a something like this:
https://stackoverflow.com/a/4697712/3150636
Where you detect the arguments passed in using func_num_args and branch from there.
Solution 2:[2]
Since PHP 8.0 there has been support for Union types in PHP:
public static function linkClient(Request|string $request, $string2){
if ($request instanceof Request){
$data = $request->all();
//do things to request
} else {
//do string things to $request
}
}
The downside is that there's no built-in mechanism to ensure that you either call the function with a single Request parameter or two string parameters as the check is only on the first parameter.
Solution 3:[3]
Use splat operator. https://lornajane.net/posts/2014/php-5-6-and-the-splat-operator
public static function linkClient(...$paras)
{
if (count($paras) == 1) {
echo 'Request $request passed';
return;
}
echo 'Strings passed';
print_r($paras);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ben |
| Solution 2 | apokryfos |
| Solution 3 | Maik Lowrey |
