PHP对象方法不像我期望的那样

0 php arrays reference

我不太明白为什么这段代码的输出为'1'.我的猜测是php的行为与我以前使用的大多数其他OO语言不同,因为php使用的数组不能是对象.更改类返回的数组不会更改类中的数组.我如何让类返回一个我可以编辑的数组(并且具有与类中的一个相同的地址)?

<?php
    class Test
    {
        public $arr;
        public function __construct()
        {
            $this->arr = array();
        }

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

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

    $t = new Test();
    $data = 5;
    $t->addToArr($data);

    $tobj_arr = $t->getArr();
    unset($tobj_arr[0]);

    $tobj_arr_fresh = $t->getArr();
    echo count($tobj_arr_fresh);
?>
Run Code Online (Sandbox Code Playgroud)

编辑:我预计输出为0

Ikk*_*kke 6

您必须通过引用返回数组.这样,php返回对数组的引用,而不是副本.

<?php
    class Test
    {
        public $arr;
        public function __construct()
        {
            $this->arr = array();
        }

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

        public function & getArr() //Returning by reference here
        {
            return $this->arr;
        }
    }

    $t = new Test();
    $data = 5;
    $t->addToArr($data);

    $tobj_arr = &$t->getArr(); //Reference binding here
    unset($tobj_arr[0]);

    $tobj_arr_fresh = $t->getArr();
    echo count($tobj_arr_fresh);
?>
Run Code Online (Sandbox Code Playgroud)

返回0.

返回的引用子页面:

与参数传递不同,这里你必须在两个地方使用& - 表示你想通过引用返回,而不是副本,并指示应该完成引用绑定而不是通常的赋值

请注意,虽然这可以完成工作,但问题是它是否是一个好习惯.通过更改类本身之外的类成员,跟踪应用程序变得非常困难.