dongxiong1941 2013-11-16 07:39
浏览 43
已采纳

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

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?

  • 写回答

5条回答 默认 最新

  • dovgqc2648 2013-11-16 07:46
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥15 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)