How do I make a variable to become an object?

0

Model:

public function gettoken() {
    $token = $this->db->get('token');
    return $token->result();

Controller

$this->load->model('Mod_login');
$get = $this->Mode_login->gettoken();
echo $get->datta;

So I wanted to learn how do I get my $ variable to become an object so that I can get the data from the compo of the table in question datta. How do I do that?

    
asked by anonymous 03.09.2016 / 03:59

1 answer

0

As follows:

$this->load->model('Mod_login');
$get = $this->Mode_login->gettoken();
echo $get[0]->datta;

The result method of Codeigniter Active Record Class returns an array with the results of the database in object format, so you can access them as follows:

echo $get[0]->datta;

You could leave your code as follows to access the object the way you want it:

$this->load->model('Mod_login');
$listaResultados = $this->Mode_login->gettoken();
$get = $arrayResultado[0];
echo $get->datta;

In these codes shown above, an error can certainly occur if no database records are returned and if you try to access the index number 0 of the $arrayResultado[0] array, then to deal with and solve this, you can make the following solution:

$this->load->model('Mod_login');
$listaResultados = $this->Mode_login->gettoken();

//Verifica se existe algum elemento no array $listaResultados.
if (count($listaResultados) > 0) {
    $get = $arrayResultado[0];
    echo $get->datta;
}

Remembering that in PHP the typing of variables is dynamic, so for a variable to be an object, simply assign an object to it.

    
03.09.2016 / 04:14