如果我的类结构的值可以是true或false,那么不会改变,当前实现为变量会更好地将它们更改为常量,例如:
class Parent {
const BOOL_CONST = false;
...
}
class SomeChild extends Parent {
const BOOL_CONST = true;
...
}
后来我有一个对象,可以是该类层次结构中的任何类型,父项或其子项之一,并且某些子项可能像“SomeChild”一样将值重载为true.
有没有办法在不知道课程的情况下访问常量?换句话说,我可以这样做:
$object->BOOL_CONST
或者将这些值保留为变量会更好,即使它们真的不应该改变?
UPDATE
我已经对上面的问题进行了重写,以便更好地表达我试图提出的问题.
解决方法:
PHP 5.3现在接受该对象作为类引用:$this :: BOOL_CONST现在已被接受.
//
// http://php.net/manual/en/language.oop5.constants.php
//
// As of PHP 5.3.0, it's possible to
// reference the class using a variable.
// The variable's value can not be a keyword
// (e.g. self, parent and static).
//
// I renamed "Parent" class name to "constantes"
// because the classname "Parent" can be confused with "parent::" scope
class constantes
{
const test = false;
}
// I renamed "SomeChild" too, with no reason...
class OverloadConst extends constantes
{
const test = true;
public function waysToGetTheConstant()
{
var_dump(array('$this'=>$this::test)); // true, also usable outside the class
var_dump(array('self::'=>self::test)); // true, only usable inside the class
var_dump(array('parent::'=>parent::test)); // false, only usable inside the class
var_dump(array('static::'=>static::test)); // true, should be in class's static methods, see http://php.net/manual/en/language.oop5.late-static-bindings.php
}
}
// Classic way: use the class name
var_dump(array('Using classname' => OverloadConst::test));
// PHP 5.3 way: use the object
$object = new OverloadConst();
var_dump(array('Using object' => $object::test));
$object->waysToGetTheConstant();
请注意,您可以覆盖类常量,但不能覆盖接口常量.
如果constantes是OverloadConsts实现的接口,那么您不能覆盖其const测试(或BOOL_CONST).
来源
标签:php,oop,override,class-constants
来源: https://codeday.me/bug/20190715/1470060.html