Question

I have a Callback function, that, the second parameter is an Array. So, I have something like:

public function foo ($something, $callback) {
  /**
   * function body
   */
  $booleanOrArray = $this->bar();

  if ( is_callable ( $callback ) ) {
    return call_user_func ( $callback, !is_array($booleanOrArray), $booleanOrArray || [ ]);
  }
  throw new Exception('A callback function must be defined.');
}

So, in the call_user_func, there's a var that is called $booleanOrArray. This is because, if the procces of the function bar is well done, then, returns an Array with data, otherwise, the bar function returns false; so, if bar returns false, the first parameter in the callback function is determined by is_array($booleanOrArray), so, if foo returns false, there is an error, and, if is an Array, this param will be false.

But, in my app, I force to the user to define the callback function as follows:

$MyClass = new ClassInstance();
$MyClass->foo('firstParam', function ( $error, Array $data ) {
  if ( ! $error ) {
    var_dump($data);
  }
  else {
    print 'Hey!';
  }
});

But, after all these code, I was surprised to realize that $booleanOrArray || [ ] always returns false.

In Javascript, if I code var x = foo || bar;, if foo is null, or false, or undefined, then x will have the bar value, and vice versa.

So, the question:

  • Is this possible in php, or I have to do something like $x = ($booleanOrArray) ? $booleanOrArray : [ ] ?

  • Do you have any idea to improve the callback function in this case? (not opinion based, only standards)

Was it helpful?

Solution

something like $x = ($booleanOrArray) ? $booleanOrArray : [ ] ?.

Yes, you can even use shortened ternary syntax:

$booleanOrArray ?: []

This results in $booleanOrArray if it is not falsy or empty array otherwise.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top