PHP评估类子成员

时间:2018-02-12 13:29:34

标签: php

class Customer{
    public $country;
    public function __construct(){
      $this->country = new Country();
      $this->country->name = "USA";
   }

}

class Country{

}

我想打印国家/地区名称,但我只有以下背景信息。

 $c = new Customer();
 $member = "country.name";// i cant decide on this, this is what i get as a parameter

您能否建议我如何使用提供的country.name字符串打印国家/地区名称?

此处构建的解决方案适用于电子邮件模板

"the country that good for you is {country.name}"

所以我会在$c$member

的帮助下将country.name替换为USA

1 个答案:

答案 0 :(得分:1)

您可以通过遍历$members字符串中的元素并逐步进入对象来实现此目的:

// First initialise our reference to the "top-level" object
$ref = $c;
// Break apart our steps
$steps = explode('.', $members);

// For every element in the array, dig deeper into the object hierarchy
while ($step = array_shift($steps)) {
    $ref = $ref->{$step};
}

// Once the loop is finished, $ref will be set to $c->country->name
echo $ref;

请参阅https://eval.in/954722