为什么只有一个赋值时数组中的两个元素?

In my PHP(5.4.19) app, I assigned string values to two different arrays. One array is scoped to the method, and the other array is a class property:

class AnyClass{
   public $foo = array();

   public function anyMethod(){
       $bar = array();
       $bar[]       = 'anyTextA';
       $this->foo[] = 'anyTextB';
       return array( $bar, $this->foo );
   }
}

Here is what anyMethod() returns:

Array
    (
        [0] => Array
            (
                [0] => anyTextA
            )

        [1] => Array
            (
                [0] => anyTextB
                [1] => anyTextB
            )

    )

Why are two elements appearing in the second array when only one assignment has taken place?

You must be calling this method more than 1 time.

$this->foo[] = 'anyTextB';

This statement adds one more entry to $this->foo whereas the other statement $bar = array(); creates a new array everytime. So if you run this method two times, you will get two values for $foo but still one value for $bar.

As I asked in the first comment, if you show us how you are creating an instance of that class we will be better able to tell exactly where are you duplicating the call.

Contrary to what is being suggested elsewhere, do not use $this->foo=array();. Debug your issue and resolve what's wrong, rather than just putting up a temporary fix to hide the mistake and build more code upon it.

Try like this .. and you will get what you are expecting to get.

$var = new AnyClass;
var_dump($var->anyMethod());

OUTPUT :

array(2) {
  [0]=>
  array(1) {
    [0]=>
    string(8) "anyTextA"
  }
  [1]=>
  array(1) {
    [0]=>
    string(8) "anyTextB"
  }
}

You are calling the method twice.

This could be because you are calling the method before AND while you are trying to echo the results.

But it could also be because you are working in an IDE, and the IDE has the method set in the Watch list, for example.

You may be call anyMethod() twice.

Try to add an index in the array foo.

For example: $this->foo[1] = 'anyTextB';

The problem should not happen again.

The number of assignments in your $foo array depends on the number of times the anyMethod() gets executed

i.e. if anyMethod() gets executed once, it will contain only one value inside and if anyMethod() gets executed 5 times, it will contain 5 values inside

As your $foo array is scoped outside the anyMethod(), values get added to it every time you execute the anyMethod() function

But in case of the $bar array, its scoped inside the anyMethod(). It initializes the $bar to a new array every time the anyMethod() executes

If you want to avoid this problem

use this line $foo = array(); inside your anyMethod()