PHP不允许
class Foo
{
private const my_private_const;
但当然允许
const my_const;
实际上常数是全局的,因为我可以用Foo::my_const
在任何地方访问my_const
个
有没有办法使私有常量成为私有常量?
PHP不允许
class Foo
{
private const my_private_const;
但当然允许
const my_const;
实际上常数是全局的,因为我可以用Foo::my_const
在任何地方访问my_const
个
有没有办法使私有常量成为私有常量?
答案是简单的"不".PHP不支持这个概念.你能做的最好的事情就是在类中设置一个private static
变量,这当然没有那么好,因为它不是只读的.但你必须克服它.
Edit
你的问题让我思考——以下是我从未try 过的东西,但可能有用.换句话说,"这是未经测试的".但假设你想要一个名为FOO
的"私有常数":
// "Constant" definitions
private function __get($constName){
// Null for non-defined "constants"
$val = null;
switch($constName){
case 'FOO':
$val = 'MY CONSTANT UNCHANGEABLE VALUE';
break;
case 'BAR':
$val = 'MY OTHER CONSTANT VALUE';
break;
}
return $val;
}
当然,你的语法看起来有点奇怪:
// Retrieve the "constant"
$foo = $this->FOO;
...但至少这行不通:
$this->FOO = 'illegal!';
也许有什么值得一试的?
干杯