Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP: something wrong with this closure syntax?

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 \"&quot;$txt&quot;\";"));
?>

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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) => , "&quot;$txt&quot;");
?>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading