Search code examples
phpfunctionescapingfunction-parameter

Why Must This Function That Escapes HTML Have A Parameter Initially Set That Is An Empty String - PHP?


I've seen a function that escapes outputted HTML onto a page, by returning the htmlspecialchars() method inside a function:

 function escape($string="") {
      return htmlspecialchars($string);
 }

The tutorial said to always set the parameter to an empty string: $string = ""

Why must you do this? Surely the following function would work just as well?

 function escape($string) {
      return htmlspecialchars($string);
 }

In both cases you would call the function with something like the following after you have fetched a row/record from a database:

$db_id = escape($row['id']);

I don't understand why the parameter must initially be given the value of an empty string?

Anna


Solution

  • Try running the code blocks given below

    function 1: Param is optional

    <?php 
    error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
    function escape($string="") {
          return htmlspecialchars($string);
     }
    
    echo escape();
    ?> 
    

    function 1: Param is NOT optional

    <?php 
    error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
    function escape($string) {
          return htmlspecialchars($string);
     }
    
    echo escape();
    ?> 
    

    The second function will throw an error Fatal error: Uncaught ArgumentCountError: Too few arguments to function escape(), 0 passed in

    Refer php.net

    enter image description here