【问题标题】:PHP array Reference Bug?PHP数组参考Bug?
【发布时间】:2010-08-27 17:20:36
【问题描述】:

使用 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

【问题讨论】:

    标签: php arrays pass-by-reference php-5.3


    【解决方案1】:

    你可能想要的是这个:

    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;
    

    【讨论】:

    • > 您不需要“在调用时要求参考”,我认为它仅适用于对象。是的,但是如果函数返回引用,为什么我需要另一个&amp;?毫无意义,为什么&amp;$this-&gt;_storage[count($this-&gt;_storage)-1]崩溃?
    • @user 因为= 是赋值运算符,它不会通过引用进行赋值。如果您使用$a = 1; $b =&amp; $a; $c = $b$c 也不会成为参考。就是那样子;如果你想通过引用分配,你必须使用=&amp;。你是什​​么意思“崩溃”?有段错误?
    • @user 你能发布一个重现问题的小脚本并将其发布到某个地方(例如 pastebin)吗?
    猜你喜欢
    • 2014-11-23
    • 2019-11-29
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    相关资源
    最近更新 更多