如何在Php中获得一个Final类的Protected的static成员属性

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

你可能感兴趣的:(php)