1

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
   }
 }
apokryfos
  • 38,771
  • 9
  • 70
  • 114
bart2puck
  • 2,432
  • 3
  • 27
  • 53

3 Answers3

0

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.

Ben
  • 2,962
  • 2
  • 20
  • 26
  • So I would assume this is a bad idea. is it bad code to have a second function virtually exact like the first except for the (params)? – bart2puck Jan 27 '22 at 16:10
0

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.

apokryfos
  • 38,771
  • 9
  • 70
  • 114
0

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);
}
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79