user1919
user1919

Reputation: 3938

Access values in PHP object

I have the following PHP object, which I want to access specific values from it but I have difficulties in understanding how to start:

   kamranahmedse\Geocode Object (
     [service_url:kamranahmedse\Geocode:private] => http://maps.googleapis.com/maps/api/geocode/json?sensor=false
     [service_results:kamranahmedse\Geocode:private] => stdClass Object (
       [results] => Array (
         [0] => stdClass Object (
           [address_components] => Array (
             [0] => stdClass Object (
               [long_name] => 112
               [short_name] => 112
               [types] => Array (
                 [0] => street_number
               )
             )
             [1] => stdClass Object (
               [long_name] => Imittou
               [short_name] => Imittou
               [types] => Array (
                 [0] => route
               )
             )
             [2] => stdClass Object (
               [long_name] => Cholargos
               [short_name] => Cholargos
               [types] => Array (
                 [0] => locality
                 [1] => political
               )
             )
             [3] => stdClass Object (
               [long_name] => Cholargos
               [short_name] => Cholargos
               [types] => Array (
                 [0] => administrative_area_level_5
                 [1] => political
               )
             ) ...

For example how can I access:

[long_name] => Cholargos

Upvotes: 0

Views: 73

Answers (1)

James Pudney
James Pudney

Reputation: 70

The variable you're trying to access is private and therefore you're not going to be able to access it directly.

A better way is to use the methods provided by the class you're using. Looking at the code you've provided I can see that you're using https://github.com/kamranahmedse/php-geocode

Here's an example of how it can be used to get the locality:

<?php

require __DIR__."/vendor/autoload.php";

use kamranahmedse\Geocode;

$address = "Imittou 112 Cholargos 155 61 Greece";

$geocode = new Geocode($address);

echo $geocode->getLocality();

Also, looking at the class source code we can see that when the address information is retrieved and local variables populated the long_name is used to populate the locality, which is what you want:

$this->locality = $component->long_name;

So the above code example should answer your question.

Upvotes: 3

Related Questions