PHP 数组参考 Bug?
使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能想要的是这样的:
What you probably want is this: