如何在此代码中从每个对象打印/回显/获取所有属性?

时间:2019-07-14 22:03:30

标签: php object foreach properties attributes

如何在此代码中打印/回显所有Country对象的所有属性/属性值?我曾想过使用“ foreach”,但我不知道具体含义。 echo语句在代码的最后一行。 谢谢!

    <?php

   class Country {
  public $nombre;
  public $poblacion;
  public $idioma;
  public $moneda;
  public $economia;
  public $deporte;


}

$country1 = new Country ();
$country1->nombre = 'Argentina';
$country1->poblacion = '40 millones';
$country1->idioma = 'Castellano';
$country1->moneda = 'Peso argentino';
$country1->economia = 'Agro';
$country1->deporte = 'Futbol';

$country2 = new Country ();
$country2->nombre = 'USA';
$country2->poblacion = '200 millones';
$country2->idioma = 'Ingles';
$country2->moneda = 'Dolar estadounidense';
$country2->economia = 'Multiples industrias';
$country2->deporte = 'Basket,Baseball,Futbol Americano';

$country3 = new Country ();
$country3->nombre = 'Alemania';
$country3->poblacion = '50 millones';
$country3->idioma = 'Aleman';
$country3->moneda = 'Euro';
$country3->economia = 'Multiples industrias';
$country3->deporte = 'Futbol';


$countries = [$country1,$country2,$country3];

foreach ($countries as $country)
{


  **echo $country->¿? "<br>";**

}  

1 个答案:

答案 0 :(得分:0)

foreach ($countries as $country) {
    foreach ($country as $k => $v) {
        echo $k . ': ' . $v . '<br>'; // nombre: Argentina ...
    }
}