<?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();