How to create overload in PHP by means of variadic-function?

0

Here's my problem: For reasons of debug I decided to create a function that would return me a% formatted format without the need for a gambiarra (ie , without creating the print_r . That way, I would transform this:

<?php
   echo "<pre>";
   print_r($array);
   echo "</pre>";
?>

In this:

<?php printr($array); //onde a função *printr* foi criada por mim. ?>

But ... For me that was not enough, I wanted to have two methods <pre>/<pre> : one that only received one parameter and actually printed on the screen; another one that received two parameters, where one wrote a message like System Debug , and another that printed printr the way it wanted. Here's how I ask myself, how do I do this, knowing that PHP does not allow me to create two methods with the same name?

    
asked by anonymous 17.11.2017 / 18:38

1 answer

0

Here I find my answer: variadic-function . Basically, PHP has a resource in which I do not delimit the number of parameters within my function. This causes me to put a different number of parameters per call, which was exactly what I wanted! The basic syntax of this concept would be:

<?php
   /*
    Esses 3 pontinhos simbolizam basicamente, que todos os elementos que
    eu colocar dentro dessa variável será armazenado em um array com o 
    limite sendo a quantidade de parâmetros utilizados.
   */
   function valores(...$parametros){
      foreach($parametros as $chave => $valor){
         echo "O parametro".$chave."é:".$valor;
      }

     $a = valores("Hello"); //essa função retorna "O Parametro 0 é Hello".
     $b = valores("Hello","World"); // essa função retorna "O Parametro 0 é Hello.O Parametro 1 é World".
   }
?>

So, now just put the values I want it to print, right?

public function valores(...$parameter){
    if(count($parameter) == 1){
        echo "<pre>";
        print_r($parameter[0]);
        echo "</pre>";
    } else if (count($parameter) == 2){
        echo "<h1>";
        echo $parameter[0];
        echo "</h1>";
        echo "<pre>";
        print_r($parameter[1]);
        echo "</pre>";
    }
}

This function works perfectly! Any tip / opinion is welcome! I hope you share your knowledge with me too

    
17.11.2017 / 18:38