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
答案 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;