共计 1269 个字符,预计需要花费 4 分钟才能阅读完成。
<?php
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′?
谬误形式 1
class test extends ConstantOne{
}
ECHO test::init_ERRNO_OK();
形式 1 起因:
PHP Fatal error: Class test may not inherit from final class (ConstantOne)
谬误形式 2
var_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();
正文完