Home >Backend Development >PHP Tutorial >array作为类属性,无法赋值?

array作为类属性,无法赋值?

WBOY
WBOYOriginal
2016-06-06 20:42:331185browse

假设有类

<code><?php class MyClass {
    protected $arr;

    public function __construct() {
        $this->arr = array();
    }

    public function getArr() {
        return $this->arr;
    }

    public function append($arr) {
        $this->arr[] = $arr;
    }

    public function merge($arr) {
        $this->arr = array_merge($this->arr, $arr);
    }
}
</code>

2个函数调用的效果不同

<code><?php $arr = array('a','b');
$obj = new MyClass();

$obj->append($arr);//使用append无法修改类属性
var_dump($obj->getArr());
//output : 
//array(0){}

$obj->merge($arr);//使用merge可以
var_dump($obj->getArr());
//output:
//array(2){'a','b'}
</code>

这是为什么?

回复内容:

假设有类

<code><?php class MyClass {
    protected $arr;

    public function __construct() {
        $this->arr = array();
    }

    public function getArr() {
        return $this->arr;
    }

    public function append($arr) {
        $this->arr[] = $arr;
    }

    public function merge($arr) {
        $this->arr = array_merge($this->arr, $arr);
    }
}
</code>

2个函数调用的效果不同

<code><?php $arr = array('a','b');
$obj = new MyClass();

$obj->append($arr);//使用append无法修改类属性
var_dump($obj->getArr());
//output : 
//array(0){}

$obj->merge($arr);//使用merge可以
var_dump($obj->getArr());
//output:
//array(2){'a','b'}
</code>

这是为什么?

http://3v4l.org/Di7gT

似乎一切正常

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn