How to create PHP overload via variadic-Function?

Asked

Viewed 64 times

0

This is my problem : for the sake of debug I decided to create a function that would return me a print_r formatted without the need for a gambiarra (that is, without creating the <pre>/<pre>. That way, I’d turn it:

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

In that:

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

But... For me that wasn’t enough, I wanted to have two methods printr: one that received only one parameter and actually printed on the screen; another that received two parameters, where one wrote a message as System Debug , and another to print the print_r as I wished.
Behold, I ask myself, how do I do this, knowing that the PHP does not allow me to create two methods with the same name?

  • It may be what you wanted, but this has nothing to do with overloading.

  • So I think my concepts are wrong, could you create an example using this concept?

  • I’m new in the field, and this is the only way I’ve found to solve this problem

  • PHP must not overload.

  • Exactly! That was the only efficient way I found of dribble this problem.

  • Go back to my first comment, we’re in loop.

Show 1 more comment

1 answer

0

Behold, I find my answer : variadic-function.
Basically, the PHP has a feature in which I do not delimit the number of parameters within my function. This makes it possible for 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 as well

Browser other questions tagged

You are not signed in. Login or sign up in order to post.