cs.punk Posted September 22, 2011 Share Posted September 22, 2011 <?php class constantTest { const HELLOWORLD = 'maybe not'; function __construct() { echo HELLOWORLD; // Output: HELLOWORLD echo constant('HELLOWORLD'); // Output: Warning: constant() [function.constant]: Couldn't find constant HELLOWORLD echo self::HELLOWORLD . "\n"; // Output: maybe not } } $bob = new constantTest(); I have read through the manual but as far as I can see all three methods should output the constant rather than just the last one. Question: Why? Quote Link to comment https://forums.phpfreaks.com/topic/247659-class-constants/ Share on other sites More sharing options...
Buddski Posted September 22, 2011 Share Posted September 22, 2011 I believe it is because the first 2 examples you attempted are looking in the global scope for the constant. Like superglobals, the scope of a constant is global. You can access constants anywhere in your script without regard to scope. For more information on scope, read the manual section on variable scope. So to reference the HELLOWORLD constant inside your class you should call self:: as your third example shows. Quote Link to comment https://forums.phpfreaks.com/topic/247659-class-constants/#findComment-1271782 Share on other sites More sharing options...
requinix Posted September 22, 2011 Share Posted September 22, 2011 As the manual page says, constant will work with class constants as long as you prefix the class name. echo constant(__CLASS__ . "::HELLOWORLD"); Quote Link to comment https://forums.phpfreaks.com/topic/247659-class-constants/#findComment-1271791 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.