علة مرجع صفيف PHP؟
-
01-10-2019 - |
سؤال
مع 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
المحلول
ما تريده هو هذا:
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;
لا تنتمي إلى StackOverflow