Variable passed to view does not contain the set value

Asked

Viewed 47 times

0

I am creating a PHP framework and in my Controller class, I have a method render, where I receive two parameters, the filename (which would be the view), and an array of variables that will be passed to that view.

function render($arquivo, $variaveis = [])
{
    extract($variaveis); // extrai as variáveis que serão passadas para a view

    require $arquivo;
}

These variables will be passed to the view this way:

$variavel1 = 'teste1';
$variavel2 = 'teste2';

$this->render('minha-view.php', compact('variavel1', 'variavel2'));

The problem

If I have a variable $arquivo in my controller, and the value of that variable is any string, the value that is passed to my view would be the first parameter that was passed to the method render. Example:

meucontrolador.php

$arquivo = 'arquivo.xyz.txt';

// passa a variável $arquivo para a view minha-view.php
$this->render('minha-view.php', compact('arquivo'));

my-view.php

<body>
    <?php echo $arquivo; ?> <!-- ao invés de imprimir 'arquivo.xyz.txt' ele imprime 'minha-view.php' -->
</body>

Thanks in advance.

1 answer

0

Do not use the Compact() function use the Extract() function it already predicts this problem and allows you to define a prefix in these cases where there are variables with the same name, because php will always prioritize the created variable first.

This solves your problem, but you’ll need to use a single variable and centralize your data for extraction in an array, which will also save you effort as you won’t have to dictate every variable you’ve created to be extracted, the function will go through the array and take care of the rest.

In case to create a $file variable you will do as follows.

// Cria um array vazio
$data = [];    

// Cria uma chave contendo o nome do arquivo
$data['arquivo'] = 'arquivo.xyz.txt';

// Passa o array para extração e define um prefixo caso já exista uma variavel com mesmo nome
extract($data, EXTR_PREFIX_SAME, "prefixo");

When you print the value you will have a variable created with the same name as the array key

echo $arquivo;

Or

If there is a variable already created before extraction

echo $prefixo_arquivo;

I hope I’ve helped!

Browser other questions tagged

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