php 类常量覆盖,在PHP中使用类常量和重写

如果我的类结构的值可以是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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值