Alexander Alexander - 1 year ago 83
PHP Question

Access constants inside namespace with a dynamic name

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";

So the question remains, how can i access namespaced constants without a helper function ?

P.S constant names are same for each file

lku lku
Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download