Sebastian Boender
Sebastian Boender

Reputation: 11

Variables not passing to class (PHP)

I am trying to pass a JSON response from an external API to a class in a different file. Somehow it's not storing in the class. I've tried var_dumping the class like this:

$user->country_ip = $country_ip; die(var_dump($user->country_ip));

It somehow doesn't work. But, when I try to vardump the actual variable like this:

die(var_dump($country_ip));

Then it does work, so the variable is fine. I'm very confused, does anyone have an answer to this? It's midnight here, it might be something small?

Upvotes: 0

Views: 80

Answers (1)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

A minimalist example will be like this,

class User
{
  public $country_ip;

  public function getCountryIp()
  {
    return json_decode($this->country_ip, true);
  }
}

$country_ip = '192.168.2.227';
$user = new User();
$user->country_ip= json_encode($country_ip);
var_dump($user->getCountryIp()); //It will print "192.168.2.227"

DEMO: https://3v4l.org/YSk9X

Upvotes: 1

Related Questions