开发者

Why const is undefined in static function?

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:

开发者_如何学PythonNotice: Use of undefined constant name - assumed 'name' in ...

What am I doing wrong ?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜