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

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

WBOY
Release: 2016-06-06 20:42:33
Original
1186 people have browsed it

假设有类

<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>
Copy after login
Copy after login

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>
Copy after login
Copy after login

这是为什么?

回复内容:

假设有类

<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>
Copy after login
Copy after login

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>
Copy after login
Copy after login

这是为什么?

http://3v4l.org/Di7gT

似乎一切正常

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template