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

标签 php arrays private protected

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

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

我需要这个数组可以沿着脚本访问,以允许在“配置”字段中的任何字段中进行更改。有没有办法保护数组或数组的一部分不被修改,就好像它在类中声明为私有(private)一样?我尝试将其定义为常量,但它的值在脚本执行期间会发生变化。将它实现为一个类意味着我必须从头开始重建完整的应用程序 :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,会更好:将允许捕获那些特别:-)

关于php - 如何保护 php 中的数组的一部分不被修改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1210719/

相关文章:

java - 移动部分数组中的对象

JavaScript - 无法将字典值添加到数组

c++ - protected 和私有(private)有什么区别?

Typescript - 重载私有(private)方法

arrays - 我应该使用 {} 还是 {0} 来初始化数组/结构?

php - 每个用户都应该有一个单独的孤立数据库吗?

PHP 在插入 MySQL 时向字符添加斜杠

javascript - 在 PHP 中运行 SQL 查询时自动刷新结果 div

c - 为什么在 C 中使用静态函数?

php - preg_replace() 函数问题?