使用define()d 标记访问属性?
我想这样做:
<?php
define('X', 'attribute_name');
// object $thing is created with member attribute_name
echo $thing->X;
?>
尝试$thing->X
,PHP将X作为$thing的属性,并忽略它是一个define()的事实(正确的是)令牌。考虑到这一点,我原本期望 $thing->{X}
能够工作,但没有骰子。
我想出的唯一解决方案是使用中间人变量,如下所示:
$n = X;
echo $thing->$n;
但是这个额外的步骤似乎不太像 PHP 式的。关于更优雅的解决方案有什么建议吗?
I'd like to do this:
<?php
define('X', 'attribute_name');
// object $thing is created with member attribute_name
echo $thing->X;
?>
Attempting $thing->X
, PHP takes X to be a property of $thing, and ignores the fact (rightly so) that it's a define()'d token. That in mind, I had expected $thing->{X}
to work, but no dice.
The only solution I'v come up with is to use a man-in-the-middle variable, like so:
$n = X;
echo $thing->$n;
But this extra step seems fairly un PHP-esque. Any advice on a more graceful solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
似乎对我有用。这是我的测试脚本:
输出“bar”。
seems to work for me. Here was my test script:
outputs 'bar'.