How do I make a variable become an object?

Asked

Viewed 97 times

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 to make my $get variable an object so I can get the data from the composition of the table in question Datta. How do I do that?

  • 1

    I forgot to mention that echo $get->Datta gives an error. Follows error: Message: Trying to get Property of non-object

  • This error occurs because you are trying to access a property of a variable that is not an object. In your case this variable is an array, whether empty or not, which is what the result() method returns.

1 answer

0


As follows:

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

The method result Codeigniter’s Active Record Class returns an array with the database results in object format, so you can access them like this:

echo $get[0]->datta;

You could leave your code the following way 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 record is returned and if you try to access the array number 0 index $arrayResultado[0], then to treat and solve so, you can enhance 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 variable typing is dynamic, so for a variable to be an object, simply assign an object to it.

Browser other questions tagged

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