tags:

views:

59

answers:

1

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 ?

+10  A: 

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
Thanks a lot !!
Misha Moroshko