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

3

I have a function that loads a given path with through include . The parameters of this function are $file and $data . The parameter file is the name of the file that will be loaded with include within the function, and $data is a 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 argument name that 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 error:

  

File 'other value' does not exist

How to solve this problem?

    
asked by anonymous 14.12.2015 / 14:59

1 answer

1

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

These functions are: func_get_args and func_get_arg

See:

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 a parameter in the function to then give unset and use func_get_arg ? Is not that useless code typing?"

No, because it is purposeful, since declaring the parameters always forces the second parameter $data to be array .

If I did the function without the parameters (in this case in particular), it would be difficult to document and understand that the function needs to get two arguments and that the second argument is obligatorily a array .

    
14.12.2015 / 14:59