php的final修饰类,如何在Php中获得一个Final类的Protected的static成员属性

final class ConstantOne {

static protected $ERRNO_OK;

static protected function init_ERRNO_OK() {

return 0;

}

static protected function init_ErrorMsg() {

return array(

0 => "OK",

);

}

}

请答题:

如何获取'0'?

错误方式1class test extends ConstantOne{

}

ECHO test::init_ERRNO_OK();

方式1原因:

PHP Fatal error: Class test may not inherit from final class (ConstantOne)

错误方式2var_dump(ConstantOne::init_ErrorMsg());

方式2原因:

PHP Fatal error: Uncaught Error: Call to protected method ConstantOne::init_ErrorMsg()

思考

staitc的话,我可以不实例化就可以调用,protected的话,可以实例化本类或者父类调用,但是关键是还有个final修饰。Final修饰的类不能被继承,所以只能本类调用,未实例的类调用static的方法又说是因为protected的。static本质是类的方法,

解决思路/**

* Base class for constant Management

*/

abstract class BaseConstant

{

/**

* Don't instanciate this class

*/

protected function __construct() {}

/**

* Get a constant value

* @param string $constant

* @return mixed

*/

public static function get($constant)

{

if(is_null(static::$$constant))

{

// echo sprintf('static::init_%s', $constant);

static::$$constant = call_user_func(

sprintf('static::init_%s', $constant)

);

}

return static::$$constant;

}

}

final class ConstantTwo extends BaseConstant {

static protected $ERRNO_OK;

static protected function init_ERRNO_OK() {

return 100;

}

static protected function init_ErrorMsg() {

return array(

100 => "OK",

);

}

//以下这也也可以

public static function outOK (){

echo static::init_ERRNO_OK();

}

}

echo ConstantTwo::get('ERRNO_OK');

echo ConstantTwo::outOK();

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值