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 ?

Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746
  • See also [my attempt at a canonical answer for causes of this error message](http://stackoverflow.com/questions/2941169/what-does-the-php-error-message-notice-use-of-undefined-constant-mean/8025500#8025500). – John Carter Nov 06 '11 at 06:52

1 Answers1

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...

ircmaxell
  • 163,128
  • 34
  • 264
  • 314
  • 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. – Rohn Adams Aug 19 '16 at 20:57