代码之家  ›  专栏  ›  技术社区  ›  Misha Moroshko Amr Mostafa

为什么在静态函数中未定义const?

  •  2
  • Misha Moroshko Amr Mostafa  · 技术社区  · 15 年前

    为什么 name 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();
    

    我得到以下错误:

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

    1 回复  |  直到 15 年前
        1
  •  13
  •   ircmaxell    15 年前

    很简单 name 常量未定义。你定义的是 class constant

    Bar::name
    

    或者从 Bar

    self::name
    

    或者从 酒吧

    static::name
    

    因此,将呼叫改为:

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

    这应该对你有用。。。

    哦,还有一张便条。通常,命名约定是常量应全部为大写。所以应该是 const NAME = 'leo'; ,并使用 self::NAME 有

    推荐文章