0

Here's what I was doing in the past

//file: bar.php
defined('MYC') or define('MYC', 'val1');
//file: bootstrap.php
define('MYC', 'val2');

I would include bootstrap.php first which would set MYC = 'val2'.
Now bar.php is in the \Foo\Bar namespace, i.e. to say

//file: bar.php
namespace Foo\Bar;
defined('MYC') or define('MYC', 'val1');
//file: bootstrap.php
//following doesn't work
//const \Foo\Bar\MYC = 'val2';
//?? what do I do here ??
3
  • You code should still work regardless of namespace because define() function defines global constants, they are visible in any namespace. Commented Oct 31, 2011 at 12:53
  • thanks, I got that by experimenting, and I also figured I can't do conditional const MYC = 'val1'; in namespace Foo\Bar; so I guess I will have to live with shitty_long_namespaced_global_constant_names :( Commented Oct 31, 2011 at 13:11
  • define() isn't namespace aware. You'd have to do define (__NAMESPACE__ . '\CONST_IN_NAME_SPACE') to get it to create a constant in the current namespace. Alternatively, you can use const if you don't have to calculate the value of the constant before defining it. Commented Nov 2, 2013 at 9:24

1 Answer 1

1

Just define the key to have the namespace in the name.

Sign up to request clarification or add additional context in comments.

2 Comments

do these constants defined by define() always land up in global namespace ? it looks like so, let me dig in and report back
looks like, define('MYC1', 'val1') in any namespace is MYC1 constant, where as const MYC2 in namespace Foo\Bar is actually \Foo\Bar\MYC2 , and there is no way I can do const \Foo\Bar\MYC2 outside \Foo\Bar, so all that jazz about constants within their own namespace is NOT going to work for me :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.