I'm following along an old book and am on an exercise using function_exists
here's the code for the exercise
<?php
function tagWrap($tag, $txt, $func = "") {
if ((!empty($txt)) && (function_exists($func))) {
$txt = $func($txt);
return "<$tag>$txt</$tag>\n";
}
}
function underline($txt) {
return "<u>$txt</u>";
}
echo tagWrap('b', 'make me bold');
echo tagWrap('i', 'underline me too', "underline");
echo tagWrap('i', 'make me italic and quote me',
create_function("$txt", "return \""$txt"\";"));
?>
As expected, the first function call shows nothing because there's no function in the args, and the second shows correctly since the underline
function is defined, issue is with the third call with the closure: it's supposed to show the text but it doesn't.
At first i thought to myself "that's silly, i'm ceating a function but am passing return as a string", but messing with it just left my IDE screaming at me so i guess PHP does work like that, so i've been messing around with '' "" and `` for a while now but there's no way for the third function call to show output.
Am i creating the closure wrong or is this a simple syntax issue when passing the strings?
The argument to function_exists()
must be a string, which is looked up as a function name. You can't pass a closure to it. The correct test should be is_callable()
, it will be true for a function name, an array [object, method_name]
, or a closure.
Since create_function()
is obsolete, you should use an anonymous function or arrow function.
<?php
function tagWrap($tag, $txt, $func = "") {
if ((!empty($txt)) && (is_callable($func))) {
$txt = $func($txt);
return "<$tag>$txt</$tag>\n";
}
}
function underline($txt) {
return "<u>$txt</u>";
}
echo tagWrap('b', 'make me bold');
echo tagWrap('i', 'underline me too', "underline");
echo tagWrap('i', 'make me italic and quote me',
fn($txt) => , ""$txt"");
?>