问题说的都是真的.
我在父类中定义了常量.我试过了,$this->CONSTANT_1但它不起作用.
class MyParentClass{
const CONSTANT_1=1
}
class MyChildClass extends MyParentClass{
//want to access CONSTANT_1
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*yva 23
我想你需要像这样访问它:
self::CONSTANT_1;
Run Code Online (Sandbox Code Playgroud)
如上所述,或"父母".
有一点值得注意的是,您实际上可以覆盖子类中的const值.
parent::CONSTANT_1;
Run Code Online (Sandbox Code Playgroud)
您还可以使用静态键从父方法访问子节点中的常量定义.
<?php
class Foo {
public function bar() {
var_dump(static::A);
}
}
class Baz extends Foo {
const A = 'FooBarBaz';
public function __construct() {
$this->bar();
}
}
new Baz;
Run Code Online (Sandbox Code Playgroud)
您不必使用parent. 您可以使用self它首先检查自身是否存在constant同名class,然后它会尝试访问parents constant.
Soself更通用,并且提供了“覆盖”的可能性parents constant,而无需实际覆盖它,因为您仍然可以通过 显式访问它parent::。
以下结构:
<?php
class parentClass {
const MY_CONST = 12;
}
class childClass extends parentClass {
public function getConst() {
return self::MY_CONST;
}
public function getParentConst() {
return parent::MY_CONST;
}
}
class otherChild extends parentClass {
const MY_CONST = 200;
public function getConst() {
return self::MY_CONST;
}
public function getParentConst() {
return parent::MY_CONST;
}
}
Run Code Online (Sandbox Code Playgroud)
导致以下结果:
$childClass = new childClass();
$otherChild = new otherChild();
echo childClass::MY_CONST; // 12
echo otherChild::MY_CONST; // 200
echo $childClass->getConst(); // 12
echo $otherChild->getConst(); // 200
echo $childClass->getParentConst(); // 12
echo $otherChild->getParentConst(); // 12
Run Code Online (Sandbox Code Playgroud)