views:

26

answers:

1

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?

+4  A: 
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'.

Tim Fountain
Yeah... now this is working for me as well. Must have been something else - at any rate, thanks; I'm glad to know I'm not completely insane yet!
Chris