Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - print namespace constant within a string?

I have the following test code:

namespace Test {
    const ONE = 50;

    class A {
        const TWO = 5;

        public function pA($string) {
            return $string;
        }
    }

    $a = new A();
    print $a->pA($a::TWO);
    print "This is a string: {$a->pA($a::TWO)}";
    print "This is a namespace constant: " . ONE;
    print "This is a namespace constant: " . \Test\ONE;
}

All of these examples work, but it's not what I'm looking for.

Can I use string composition to represent the constant like in the first two examples? I've tried many combinations like "${\Test\B}" or "${B}" or "${\B}" but, so far, no luck.

Maybe it isn't possible and I'm overdoing it, but anyway... is there a way to do that?

like image 540
Julio María Meca Hansen Avatar asked Jan 25 '26 00:01

Julio María Meca Hansen


1 Answers

This will not work. You can use $variables, functions or object method calls in double quoted string but not constants. Refer to the PHP string parsing documentation. You'll find many useful examples.

like image 56
hek2mgl Avatar answered Jan 26 '26 16:01

hek2mgl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!