Variable Constants

Guys, I’m quite familiar with the concept of “Variable Variables”, ie:

$a = "hello";
$$a = "world";

echo $a; // hello
echo $$a; // world
echo $hello; //world

However, I need to know if it’s possible to do something similar with constants, specifically class constants, and if so, how do you do it?

Basically, we have a class that has a load of constants predefined. A value is passed to one of the methods and depending on the value, I would like it to be substituted for one of the constants. Is this feasible or do I need to change the constants to properties?

Cheers all

Not sure if I understand exactly what you want to do, but perhaps the constant() function can help you? It works on class constants too.



class foo {
    const test = 'foobar!';
}

$const = 'test';

var_dump(constant('foo::'.$const));

Never mind, worked it out:


$val = constant("self::".$var);

Works a treat

Sorry, hadn’t seen your reply somehow. Wasn’t aware I could append “self::” like that, but it works perfectly. Thanks

If you want an opinion, I wouldn’t do such trickery with constants. I think most people who later read the code, would say wtf.

Edit- I read hastily and misunderstood what you were doing. I thought you had found a way to define then dynamically. You’re just reading them. I think that’s ok.

That’s a fair point. The option is that or a switch, which I thought would look even worse

I edited my post.

Oh good, thanks. I thought I’d just committed a cardinal-sin-of-PHP :smiley: I tried a few alternative ways of doing this and I didn’t like them, and this seemed like the ideal solution, but I couldn’t figure out how to do it until after Immerse’s original post. Good to know that we came up with the same ideas :smiley: