我在backburner上有这种框架项目,在这里我想强制使用Input
类来访问所有超全局变量,例如$_POST
,$_GET
和$_SERVER
。这里的recent question让我想起了这件事。
该类将做一点cleanup of the keys来确保没有恶意或意外,并提供一种访问项目的方式,而无需每次都使用isset()
的麻烦。它可能会根据配置执行其他操作,并且可能还会清除超全局变量。我也不喜欢superglobals are not read-only,我想在值中强制完整性。我希望此类专门用于此类,并希望在不使用该类时警告开发人员。
我的问题是这个,我担心答案是“否”:
当访问超全局变量之一时,是否可以将trigger an error转换为ojit_a?例如:
$myvar = $_POST['key'];
// Prints "Error: POST cannot be accessed directly, use the Input class instead"
还是写给超全局变量?
$_POST['key'] = 'myvalue';
// Prints "Error: POST data cannot be modified"
最佳答案
您可以使用ArrayAccess
范例1:
$_POST = new SUPER($_POST);
$_POST['hello'] = "Hello World"; // This would trigger error ;
示例2:
a.php?var=1&var2=2
$_GET = new SUPER($_GET);
echo $_GET['var'] ; // returns 1
echo $_GET['var2'] ; // returns 2
$_GET['var3'] = 2 ; //return error
使用的类(class)
class SUPER implements \ArrayAccess {
private $request = array();
public function __construct(array $array) {
$this->request = $array;
}
public function setRequest(array $array) {
$this->request = $array;
}
public function offsetSet($offset, $value) {
trigger_error("Error: SUPER GLOBAL data cannot be modified");
}
public function offsetExists($offset) {
return isset($this->request[$offset]);
}
public function offsetUnset($offset) {
unset($this->request[$offset]);
}
public function offsetGet($offset) {
return isset($this->request[$offset]) ? $this->request[$offset] : null;
}
}
关于php - 访问$ _POST或另一个超全局变量时是否可能触发错误?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12954656/