The PHP.net class constants page doesn’t mention anything about this, nor have I found other questions that have the answer.
I was surprised I couldn’t find the answer to this, maybe I didn’t look well enough, but is it possible to define a constant for a stdClass object like:
<?php $foo = new stdClass(); #something magic here like: const $foo->pi = 3.14; #and then get access like: echo $foo::pi;
If it isn’t possible, why is it not?
Thanks in advance.
Advertisement
Answer
No you can’t. And the reason is simple. Constants are static idempotent values created at compile time.
They are not variables.
Your syntax actually attempts to add a property/variable to an object and then utilize that as a constant, which is why you get a syntax error when you try to access it of Undefined class constant 'stdClass::pi'
If there is some reason you are attempting to do this, beyond the academic, you might want to create a new question that explains what you want and why. There are some interesting features of PHP (anonymous classes for example) that might allow you some sort of workaround, although the obvious traditional solution is just to define a base class and utilize inheritance to inherit things.
Interfaces can also define constants, so you can share constants with various classes by defining an interface with the constants you want defined and have the class implement the interface.