Move variables out of a vector in PHP

1

I have a controller that will pass view 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 page from the template 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 as $usuario and $publicacoes .

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

How to do this?

    
asked by anonymous 06.01.2016 / 15:29

1 answer

1

One option is to use extract () to turn indexes 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");
}
    
06.01.2016 / 15:40