I have a function with 2 arguments: a string, and a callable. I want the callable to be optional. See below.
function saySomething($str, $callback){
echo $str;
$res = false;
if(is_callable($callback)){
$res = $callback();
}
if($res){
echo ', I am cool';
} else {
echo ', I am not cool';
}
}
// This works as I expect
saySomething('piet');// deliberately not supplying a callback
// I want the output to be: piet, I am not cool.
// The output in this case: "piet, I am not cool."
In php 5.4 and php 7 it's possible to declare / type hint a callable in the function argument. The is_callable
wont be needed in the function body anymore. Next, if one does so then the callable argument MUST be valid, thus it is not optional anymore.
What do I want?
I want to know if it's possible to use the callable type declaration but keep it as an optional argument.
I tried this:
// This is not possible :-(
// Fatal error: Uncaught ArgumentCountError: Too few arguments to function saySomething()
function saySomething($str, callable $callback = function(){return false;}){
echo $str;
$res = $callback();
if($res){
echo ', I am cool';
} else {
echo ', I am not cool';
}
}
saySomething('piet'); // deliberately not supplying a callback
// I want the output to be: piet, I am not cool.
I want to the callable to return false when no callable was supplied at the client code.
The possible duplicate PHP 7.1 Nullable Default Function Parameter does not offer a solution for this situation.