如何保护php中的数组部分不被修改?

Jua*_*ank 2 php arrays private protected

我在php中有一个像这样的数组:

$ myArray = array('name'=>'juank','age'=> 26,'config'=> array('usertype'=>'admin','etc'=>'bla bla'));

我需要这个数组可以在脚本中访问,以允许在"config"字段中的任何字段EXCEPT中进行更改.有没有办法保护数组或数组的一部分不被修改,就像它在类中声明私有一样?我尝试将其定义为常量,但在脚本执行期间它的值会发生变化.将它作为一个类实现意味着我必须从头开始重建完整的应用程序:S

谢谢!

Pas*_*TIN 5

我不认为你可以使用"纯""真正的"数组来做到这一点.

实现这一目标的一种方法可能是使用一些实现的类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
Run Code Online (Sandbox Code Playgroud)

你必须实现一个对象new,它不是非常像数组......但是,之后,你可以将它用作数组.


当试图写入"锁定"属性时,你可以抛出一个异常,或类似的东西 - 顺便说一句,声明一个新Exception类,比如ForbiddenWriteException,会更好:会允许特别抓住那些:-)