PHP 数组参考 Bug?

发布于 2024-09-16 06:57:35 字数 769 浏览 11 评论 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

With PHP is it even Possible to Pass arrays by Reference ? or its a Bug Only for Me.

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());
?>

Expected Result:3
But The Output is: 2

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

开始看清了 2024-09-23 06:57:35

您可能想要的是这样的:

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;

What you probably want is this:

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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文