Don't understand how helpers.inc.php (Chap 6) works

The sample code in the Ninja book is:


//helpers.inc.php
<?php
function html($text)
{
return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}
function htmlout($text)
{
echo html($text);
}


Later code samples use the htmlout() function but I don’t see the html() function called and I don’t see how the htmlout works. I searched the forum and get hundreds of hits but don’t see this question.

Thank you for taking a look.

Mike Garey

Welcome to the forum. This is the right place to come with a question like this and you will get the guidance you need from the many experienced members who want to help.
You took the correct First Step by searching for the answer (or for a similar question, actually).

I have not read that book but can offer an explanation:

You will probably not see the html() function because it is “wrapped” by the htmlout() function.
Notice that htmlout() prints (echoes) the result from the other function. That is what I call a Convenience function. It simplifies the code you write elsewhere in your application.

The ability to ‘pass’ the result of one function out from another is fundamental to ALL software programming.

But in this case why have one function calling the other?


function html($text)
{
return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}
function htmlout($text)
{
echo html($text);
}

As I read it the above is the same as:


htmlout($text)
{
echo htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}

The only benefit I can see is that you can use the html() function seperatly if you want.

Notice the echo statement in htmlout? That sends the processed string to your browser. html just returns it. One assumes that return value is then combined with other strings before being echoed.

By having htmlout call html we avoid having two sets of htmlspecialchars statements. If we did have two and decided to change (for example) the encoding then there is a distinct possibility that we might forget to change both statements which can lead to interesting problems.

It’s not a very good design. I have not read the book but if it has code like this then I would suggest looking elsewhere.

That’s as I see it - html() just returns the passed-in string after it’s been through htmlspecialcharacters(), whereas htmlout() outputs the string. They are two different functions for two different jobs, depending on what you intend to do with the string afterwards.

I guess another benefit of encapsulating the htmlspecialchars() function call inside a simpler function would be for consistency of character encoding. Ensuring all invocations of htmlspecialchars() throughout the code base have the same second and third arguments filled would be more difficult than just invoking a single function with the arguments already preset (plus it would make updating the function arguments a lot easier, being in a single place only).