Reputation: 12785
Lets say i have 2 php files with namespaces :
The first:
# src/one.php
namespace foo\one;
const SOME_VALUE = "value 1";
And the second:
# src/two.php
namespace foo\two;
const SOME_VALUE = "value 2";
What i am trying to do :
require_once "src/one.php";
require_once "src/two.php";
foreach(["one", "two"] as $ns_type) {
echo foo\$ns_type\SOME_VALUE;
}
Obviously it does not work like that. I have been reading the doc's and could not find the right way to do this.
The only solution i found is to add a function to each namespace, construct a string with it's name and then call it.
$func = "foo\$ns_name\get_my_constant";
$func();
So the question remains, how can i access namespaced constants without a helper function ?
P.S constant names are same for each file
Upvotes: 1
Views: 126
Reputation: 1742
If you need to print constant value by it's dynamic name, you can try this:
echo constant("foo\\$ns_type\SOME_VALUE");
in your foreach loop.
Upvotes: 2