0

I have array

$x = [
name => "tableName",
type => "string",
allowNull => false,
isRequired => true,
isArray => false,
orderNumber => 0
]

and I would like to test if argument in function is like TYPE option in array $x

public function foo(string $fooName, array $params = NULL)
{
  // here is some code and ...

  foreach ($params AS $key => $val) {
    if (// ... now I need to test if $val is like $x['type'] = like string --> is_string($val) or !is_string($val) but how to do that ??) {
      // to do something
    }
  }
}

Is possible to do that?

I try something like

if (${'is_'.$x['type']}()($val)) { }

but this has result "Undefined variable: is_string"

Radek
  • 3
  • 4
  • You can not call functions dynaimcally like you can access variables dynamically. Better idea is to create an if else block handling the different datatypes. – Jesse Schokker Feb 23 '20 at 11:31
  • Have a look at this: https://stackoverflow.com/questions/1005857/how-to-call-a-function-from-a-string-stored-in-a-variable – Nergal Feb 23 '20 at 11:59
  • Does this answer your question? [How to call a function from a string stored in a variable?](https://stackoverflow.com/questions/1005857/how-to-call-a-function-from-a-string-stored-in-a-variable) – Nergal Feb 23 '20 at 12:00
  • 2
    @JesseSchokker That actually is not true... – arkascha Feb 23 '20 at 12:46
  • 1
    Take a look at `call_user_func` (https://www.php.net/manual/en/function.call-user-func.php) which easily allows such implementations. However I would strongly advise against such attempts. Such code is _very_ hard to maintain, since it is unreadable. – arkascha Feb 23 '20 at 12:48

1 Answers1

0

You can use call_user_func : the first argument is the name of your function, the second argument is the array of parameters to pass to the function :

$arr = array(
    array('type' => 'string', 'val' => "test"),
    array('type' => 'string', 'val' => 0.0),
    array('type' => 'numeric', 'val' => "test"),
    array('type' => 'numeric', 'val' => 5.0),
);

foreach($arr as $item)
{
    $fct = 'is_' . $item['type'] ; // build the function name
    
    $ret = call_user_func($fct, $item['val']); // call your build-in function
    if($ret)
        echo $item['val'] . " has type '" . $item['type'] . "'" . PHP_EOL ;
    else
        echo $item['val'] . " has not type '" . $item['type'] . "'" . PHP_EOL ;
}

Output :

test has type 'string'

0 has not type 'string'

test has not type 'numeric'

5 has type 'numeric'

Community
  • 1
  • 1
Joffrey Schmitz
  • 2,393
  • 3
  • 19
  • 28
  • Thx, this is my solution ... I know about this call_user_function, but I don't know how to do it ... thank you for simple example. – Radek Feb 23 '20 at 14:01