Move variables out of a PHP array

Asked

Viewed 39 times

1

I have a controller that will pass display information to a view, this information will be objects, and they will be passed in array.

namespace app\controllers\conteudo;

class index
{
    public function get_index()
    {
        // Supondo que eu já tenha os objetos $usuario e $publicacao instanciados e populados.

        $args = array
        (
            $usuario,
            $publicacao
        );

        $view = new \app\views\view();
        $view->pagina('publicacao', $args);
    }
}

And a function that will load a template page and display this information.

namespace app\views;

class view
{
    private $template;

    public function pagina($arquivo, $args = null)
    {
        require(getcwd() . "/app/views/templates/{$this->template}/{$arquivo}.php");
    }

}

In my template file, I can access $args[0] and $args[1], but I would not like to have access to these variables in this way, but how $usuario and $publicacoes.

I could set variables to pick up these values, but the problem is that the parameters that will be passed are uncertain, so if I pass $categoria by an array, I want to have access to $categoria in the template file.

How to do this?

1 answer

1


One option for this is to use Extract() to turn indices into variables

$arg_vars = ['categoria' => 'sapatos', 'descricao' => 'sapato de couro', 'valor' => 200];
extract($arg_vars);
echo $descricao;

Or in your project:

public function pagina($arquivo, $args = null)
{
    if(!empty($args)){
       extract($args);
    }
    require(getcwd() . "/app/views/templates/{$this->template}/{$arquivo}.php");
}

Browser other questions tagged

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