PHP求值类子成员
我想打印国家名称,但我只有以下上下文PHP求值类子成员,php,Php,我想打印国家名称,但我只有以下上下文 class Customer{ public $country; public function __construct(){ $this->country = new Country(); $this->country->name = "USA"; } } class Country{ } 您能建议我如何使用提供的country.name字符串打印国家名称吗 im在此构建的解决方案用于
class Customer{
public $country;
public function __construct(){
$this->country = new Country();
$this->country->name = "USA";
}
}
class Country{
}
您能建议我如何使用提供的country.name字符串打印国家名称吗
im在此构建的解决方案用于电子邮件模板
“对你有好处的国家是{country.name}”
因此,我将在
$c
和$member的帮助下,将country.name替换为USA。您可以通过迭代$members
字符串中的元素来实现这一点,每次都进一步进入对象:
$c = new Customer();
$member = "country.name";// i cant decide on this, this is what i get as a parameter
请参见将$members
传递到\u构造<代码>$c->国家->名称=$members代码>?如果你的类有公共成员,那么在运行时除了检查它的所有成员(如果为null!=$this->country&&!empty$this->country->name
)等之外,你真的无法执行任何不变量。当然,你可以通过构造函数强制设置,但是,仍然没有什么可以阻止一个草率或淘气的程序员在构建之后覆盖那个值。如果这些只是简单的DTO,那么这很好,但可能值得考虑使用getter的非公共属性?你似乎在使用Twig。我不知道为什么,但你的代码在你提供的链接上起作用,我收到了错误:间接修改重载属性App\Country::$name无效
我不知道这是否重要,我正在使用Laravel模型…@Shazam更新了答案以删除参考分配-我认为它现在应该可以用于Laravel模型,尽管我目前没有副本可供测试。
// 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;