3

Why the name constant is not recognised in the static function f2() ?

class Foo {
    protected static function f1($s) {
        echo "doing $s";
    }
}
class Bar extends Foo {
    const name = 'leo';
    public static function f2() {
        Foo::f1(name);
    }
}
$bar = new Bar();
$bar->f2();

I get the following error:

Notice: Use of undefined constant name - assumed 'name' in ...

What am I doing wrong ?

1

1 Answer 1

15

Quite simple, the name constant is undefined. What you defined is a class constant. You can access it through either:

Bar::name

or from within the Bar class or any of its descendants

self::name

or from within the Bar class or any of its descendants with 5.3+ only:

static::name

So, change the call to:

public static function f2() {
    Foo::f1(self::name);
}

And that should do it for you...

Oh, and one other note. Typically, the naming convention is that constants should be all uppercase. So it should be const NAME = 'leo';, and referenced using self::NAME. You don't have to do it that way, but I do think it helps readability...

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

1 Comment

Exactly what I was looking for. Many of the answers to similar questions were difficult for me to understand when to use static vs. self with class constants. This made it very clear.

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.