如何从父类函数访问子类中定义的常量?

dat*_*.io 33 php oop class

我从php.net看到这个例子:

<?php
class MyClass {

     const MY_CONST = "yonder";

     public function __construct() {

          $c = get_class( $this );
          echo $c::MY_CONST;
     }
}

class ChildClass extends MyClass {

     const MY_CONST = "bar";
}

$x = new ChildClass(); // prints 'bar'
$y = new MyClass(); // prints 'yonder'
?>
Run Code Online (Sandbox Code Playgroud)

但是$ c :: MY_CONST只能在5.3.0或更高版本中识别.我写的课可能会分发很多.

基本上,我在ChildClass中定义了一个常量,MyClass(父类)中的一个函数需要使用常量.任何的想法?

pev*_*vik 87

怎么用static::MY_CONST

  • @checksum:不,那是错的 - "self :: MY_CONST"在两种情况下打印"yonder" - 在child中定义的常量.问题是"如何从父类函数访问子类中定义的常量?". (4认同)
  • 我不明白为什么人们会在其他答案中深入研究 OOP。您的解决方案是唯一正确且更简单的解决方案 (3认同)
  • 关于实现的注意事项:`self :: MY_CONST`基于**[Late static bindings](http://www.php.net/manual/en/language.oop5.late-static-bindings.php)**,以PHP**5.3.0**发布(在git中实现[添加对Late Static Binding的支持.(Dmitry,Etienne Kneuss)](https://github.com/php/php-src/commit/166266df68db50c4d1119f2be265972c8d77f1af)) .核心实现在`get_called_class()`中.PHP <= 5.2.x给出错误`Parse error:语法错误,意外T_STATIC`. (3认同)
  • 使用`static`关键字访问`const`有些不对劲.你能解释一下为什么有效吗?PHP Docs也困惑了我.谢谢. (2认同)

Phi*_*ipp 13

自从php 5.3:

使用 static::MY_CONST


更多细节 static

在这种情况下,关键字static是对实际调用的类的引用.

这说明之间的区别static $var,static::$var以及self::$var:

class Base {
    const VALUE = 'base';

    static function testSelf() {
        // Output is always 'base', because `self::` is always class Base
        return self::VALUE;
    }

    static function testStatic() {
        // Output is variable: `static::` is a reference to the called class.
        return static::VALUE;
    }
}

class Child extends Base {
    const VALUE = 'child';
}

echo Base::testStatic();  // output: base
echo Base::testSelf();    // output: base

echo Child::testStatic(); // output: child
echo Child::testSelf();   // output: base
Run Code Online (Sandbox Code Playgroud)

另请注意,关键字static有两个完全不同的含义:

class StaticDemo {
    static function demo() {
        // Type 1: `static` defines a static variable.
        static $Var = 'bar';

        // Type 2: `static::` is a reference to the called class.
        return static::VALUE;
    }
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ris 5

代替

$c = get_class( $this );
echo $c::MY_CONST;
Run Code Online (Sandbox Code Playgroud)

做这个

$c = get_class( $this );
echo constant($c . '::MY_CONST');
Run Code Online (Sandbox Code Playgroud)