我从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?
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)
代替
$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)