-2

I have a PHP class containing a 2-dimensional array:

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

        ...
      }

The class has a method to append a specified element in the inner array:

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

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

The Prt() method simply prints the outer array:

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

I instantiate the class and try to append an element in the inner array:

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

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

However, the O/P shows an empty inner array:

Array ( [S] => A [V] => Array ( ) )
Array ( [S] => A [V] => Array ( ) )
Array ( [S] => A [V] => Array ( ) )

  1. Why is this happening? Is it related to a 'pass by value' / 'pass by reference' issue?
  2. How do I fix this?
SSteven
  • 733
  • 5
  • 17
  • 1
    Arrays in PHP aren't passed by reference, assigning them to another variables creates a copy [on write]. – deceze Aug 30 '21 at 08:31

1 Answers1

1

You try to access element 0 in an associative array you cannot do that.

public function App($elm) {
    $V = $this->cms[0]['V']; // here
F. Müller
  • 3,969
  • 8
  • 38
  • 49