php – How to make an extract inside a function without the variables colliding with the parameter variables?

Question:

I have a function that loads certain via with via include . The parameters of this function are $file and $data . The file parameter is the name of the file that will be loaded with include inside the function, and $data is an array that receives the values ​​that will be transformed into variables through the extract function.

The problem I have is the following: If the person passes array('file' => 'outra coisa') the value file will be transformed into a variable, which will collide with the name of the argument I created called $file .

Example:

function view($file, array $data) {
          ob_start();
          extract($data);
          include $file;
          return ob_get_clean();
   }

The problem:

view('meu_arquivo.php', ['file' => 'outro valor']);

The mistake:

File 'other value' does not exist

How to solve this problem?

Answer:

You can solve this by using a function that captures the arguments passed to a function, regardless of the variable name.

These functions are: func_get_args and func_get_arg

Look:

function view($file, array $data) {

          unset($file,$data); 

          ob_start();

          extract(func_get_arg(1));

          include func_get_arg(0);

          return ob_get_clean();
}

But then you might want to ask: "Wallace, why did you leave the variables declared as parameters in the function and then unset and use func_get_arg ? Isn't that pointless code typing?"

No, it's on purpose, since by declaring the parameters you always force the second parameter $data be an array .

If I made the function without the parameters (in this specific case), it would be difficult to document and understand that the function needs to take two arguments and that the second argument is obligatorily an array .

Scroll to Top
AllEscort