如何保护php中的数组部分不被修改?
题
我在php中有一个像这样的数组:
$ myArray = array('name'=>'juank','age'=> 26,'config'=> array('usertype'=>'admin','etc'=> 'bla bla'));
我需要这个数组可以在脚本中访问,以允许更改“config”中的任何字段EXCEPT。领域。有没有办法保护数组或数组的一部分不被修改,就像它在类中声明私有一样?我尝试将其定义为常量,但在脚本执行期间它的值会发生变化。将它作为一个类实现意味着我必须从头开始重建完整的应用程序:S
谢谢!
解决方案
我认为你不能用“纯粹”做到这一点。 "实"阵列。
达到此的一种方法可能使用一些实现 ArrayInterface
;你的代码看起来像是在使用数组...但实际上它会使用对象,使用访问器方法可以禁止对某些数据进行写访问,我猜...
它会让你改变一些事情 (创建一个类,实现它); 但不是一切:访问仍然会使用类似数组的语法。
,点击 这样的事情可能会成功(改编自手册):
class obj implements arrayaccess {
private $container = array();
public function __construct() {
$this->container = array(
"one" => 1,
"two" => 2,
"three" => 3,
);
}
public function offsetSet($offset, $value) {
if ($offset == 'one') {
throw new Exception('not allowed : ' . $offset);
}
$this->container[$offset] = $value;
}
public function offsetExists($offset) {
return isset($this->container[$offset]);
}
public function offsetUnset($offset) {
unset($this->container[$offset]);
}
public function offsetGet($offset) {
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
}
$a = new obj();
$a['two'] = 'glop'; // OK
var_dump($a['two']); // string 'glop' (length=4)
$a['one'] = 'boum'; // Exception: not allowed : one
你必须使用 new
来实现一个对象,它不像数组那么......但是,之后,你可以将它用作数组。
,点击
当试图写入“锁定”时属性,你可以抛出异常,或类似的东西 - 顺便说一句,声明一个新的 Exception
类,比如 ForbiddenWriteException
,会更好:会允许捕获那些<强>: - )强>
其他提示
您可以将数组设为私有,并创建一个方法来修改其内容,以检查是否有人不会尝试覆盖 config
键。
<?php
class MyClass {
private static $myArray = array(
'config' => array(...),
'name' => ...,
...
);
public static function setMyArray($key, $value) {
if ($key != 'config') {
$this::myArray[$key] = $value;
}
}
}
然后,当您想要修改您调用的数组时:
MyClass::setMyArray('foo', 'bar'); // this will work
MyClass::setMyArray('config', 'bar'); // this will be ignored
不,不幸的是,没有办法做你所描述的。变量没有任何公共或私有概念,除非它们被封装在一个对象中。
遗憾的是,您最好的解决方案是将配置重新设置为对象格式。您可以在数组中使用包含私有设置的小对象,这可能只允许您更新代码中的一些位置,具体取决于使用该部分数组的位置。