How to make an Extract within a function without the variables colliding with the parameter variables?

Asked

Viewed 87 times

3

I have a function that loads certain route through the 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 within the function, and $data is a array that receives the values that will be transformed into variables through the function extract.

The problem I have is this: If the person passes array('file' => 'outra coisa') the value file will be transformed into 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:

'Other value' file does not exist

How to solve this problem?

  • I asked that question here at SOPT knowing the answer, don’t criticize me for it. In fact as I did not have a specific question on the subject, but I just demonstrated by example, I decided to ask the question, as it is).

  • The example is here, but the question does not deal with this specific subject http://answall.com/questions/76078/include-dentro-da-classe-acesso-ao-this-self-ou-static

1 answer

1

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

Those functions are: func_get_args and func_get_arg

Behold:

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 give unset and use func_get_arg? This is not useless code typing?".

No, because it is purposeful, since declaring the parameters you always force the second parameter $data be a array.

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

Browser other questions tagged

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