有没有办法禁止变量从全局作用域中被挑选出来?
类似于:
#index.php
$forbidden = 'you should not be able to access me outside this scope'; // maybe invoke a function or namespaces?
require 'stuff.php';
echo new stuff();
#stuff.php
class stuff
{
public function __toString()
{
global $forbidden; // to result in an error or something?
/*
just a random example, but yes, any way
to somehow make a variable not global?
*/
return 'I am forbidden';
}
}不知道这是否可能,但不管怎样,我只对OOP时尚感兴趣。
原因?
禁止特定类被实例化为变量,然后从全局作用域中取出以重用其函数。让类完全“私有”,有点像一个执行所有自动化操作的主类。
希望我已经说清楚了。
发布于 2011-10-21 19:14:19
我能想到的唯一办法就是“伪造”全球范围...
//index.php
function scope() {
require 'actual.php';
}
scope();现在,将代码放在actual.php中看起来像是“普通”代码,但实际上它在函数范围内。显然,您现在不能在actual.php中声明函数或类,但在其他方面它的行为是一样的,只是声明的任何变量都在函数的作用域中,而不是全局作用域中。
但我真的不会这么做。如果有人做了像全局这样愚蠢的事情,用棍子打通常是有效的;)
https://stackoverflow.com/questions/7848572
复制相似问题