【问题标题】:accessing array from other function in a class从类中的其他函数访问数组
【发布时间】:2010-11-11 23:19:46
【问题描述】:

我在一个类中有 2 个函数,在第一个中我有类似的东西:

public function func1() {
$test = array(1,2,3);
return $test;
}

如何在第二个函数中从 $test 中复制内容?

public function func2() {
$newarray = $this->func1->test;
print_r($newarray);
}

对不起,我真的不知道怎么做这个:(

【问题讨论】:

    标签: php arrays class function accessibility


    【解决方案1】:

    你可以通过两种方式做到这一点:

    public function func2() {<br>
      $newarray = $this->func1();<br>
      print_r($newarray);<br>
    }
    

    在这种情况下,您只是调用一个函数并将结果存储到一个数组中

    public function func1() {<br>
       $this->test = array(1,2,3);<br>
    }
    
    public function func2() {<br>
      print_r($this->test);<br>
    }
    

    在这种情况下,func1 将数组存储到对象属性“test”中,而 func2 将其打印出来

    --
    大坝

    【讨论】:

    • 我会尝试第二个,因为我想将一些输出放入 func1。非常感谢。
    【解决方案2】:

    一旦一个函数完成,所有的内容都会被删除,除非你把它赋值给$this->,或者全局变量。

    因此,为了维护变量,您需要执行以下操作之一:

    Global $test;
    $this->test = $test;
    

    或者,因为你在 func1 中返回了变量,你可以将它传递给 func2

    public function func1()
    {
        $test = array(1,2,3);
        return $test;
    }
    public function func2($test)
    {
        // Do something
    }
    

    【讨论】:

      猜你喜欢
      • 2013-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-07
      • 1970-01-01
      • 2019-12-18
      相关资源
      最近更新 更多