在PHP中使用类常量和重写
发布时间:2020-12-13 22:03:30  所属栏目:PHP教程  来源:网络整理 
            导读:如果我的类结构的值可以是true或false,那么不会改变,当前实现为变量会更好地将它们更改为常量,例如: class Parent { const BOOL_CONST = false; ...}class SomeChild extends Parent { const BOOL_CONST = true; ...} 后来我有一个对象,可以是该类层次结构
                
                
                
            | 
                         
 如果我的类结构的值可以是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(); 
 请注意,您可以覆盖类常量,但不能覆盖接口常量. 来源 > PHP 5.3中的常量:http://php.net/manual/en/language.oop5.constants.php (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
