首页 > 解决方案 > 为什么我不能在 PHP 类的嵌套数组中附加元素?

问题描述

我有一个包含二维数组的 PHP 类

      class ArrApp
      {
        private $cms = [
                         'S' => 'A',
                         'V' => []
                       ];

        ...
      }

该类具有在内部数组中附加指定元素的方法:

        public function App($elm)
        {
          $V = $this->cms[0]['V'];

          array_push($V, $elm);
          $this->Prt();
        }

Prt() 方法只是打印外部数组:

        public function Prt()
        {
          print_r($this->cms);
          echo '<br>';
        }

我实例化该类并尝试在内部数组中附加一个元素:

      $aa = new ArrApp();
      $aa->Prt();

      $aa->App(1);
      $aa->Prt();

但是,O/P 显示一个空的内部数组:

数组 ( [S] => A [V] => 数组 ( ) )
数组 ( [S] => A [V] => 数组 ( ) )
数组 ( [S] => A [V] => 数组 ( ) )

  1. 为什么会这样?它与“按值传递”/“按引用传递”问题有关吗?
  2. 我该如何解决?

标签: phparrays

解决方案


您尝试访问关联数组中的元素 0,但您不能这样做。

public function App($elm) {
    $V = $this->cms[0]['V']; // here

推荐阅读