开发者

Access property with define()'d token?

开发者 https://www.devze.com 2023-01-19 01:55 出处:网络
I\'d like to do this: <?php define(\'X\', \'attribute_name\'); // object $thing is created with member attribute_name

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 solu开发者_高级运维tion?


echo $thing->{X};

seems to work for me. Here was my test script:

define('FOO', 'test');

$a = new stdClass();
$a->test = 'bar';

echo $a->{FOO};

outputs 'bar'.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号