0

使用 PHP 甚至可以通过引用传递数组吗?或者它只是我的一个错误。

class MyStack{
    private $_storage = array();

    public function push(&$elem){//See I am Storing References. Not Copy
        $this->_storage[] = $elem;
    }
    public function pop(){
        return array_pop($this->_storage);
    }
    public function top(){
        return $this->_storage[count($this->_storage)-1];
    }
    public function length(){
        return count($this->_storage);
    }
    public function isEmpty(){
        return ($this->length() == 0);
    }
}
?>
<?php
$stack = new MyStack;
$c = array(0, 1);
$stack->push($c);
$t = $stack->top();
$t[] = 2;
echo count($stack->top());
?>

预期结果:3 但输出是:2

4

1 回答 1

2

你可能想要的是这样的:

class MyStack{
    /* ... */

    /* Store a non-reference */
    public function push($elem) {
        $this->_storage[] = $elem;
    }

    /* return a reference */
    public function &top(){
        return $this->_storage[count($this->_storage)-1];
    }

    /* ...*/
}

/* You must also ask for a reference when calling */
/* ... */
$t = &$stack->top();
$t[] = 2;
于 2010-08-27T17:24:26.943 回答