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

link|improve this question

64% accept rate
feedback

1 Answer

up vote 2 down vote accepted

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;
link|improve this answer
@irc Yes, you do. See codepad.viper-7.com/kVQe4g – Artefacto Aug 27 '10 at 17:28
Fair point. I just tried. You are correct sir... (+1) – ircmaxell Aug 27 '10 at 17:29
> You don't need to "Ask for a reference when calling" I thought Its true for Objects Only. Ya It works But Why I need another & If the Function returns a reference ? meaningless and Why &$this->_storage[count($this->_storage)-1] Crashes ? – Neel Basu Aug 27 '10 at 17:34
@user Because = is the assignment operator, which doesn't do assignment by reference. If you do $a = 1; $b =& $a; $c = $b, $c won't be a reference either. That's just the way it is; if you want to assign by reference, you have to use =&. And what do you mean "crashes"? There's a segfault? – Artefacto Aug 27 '10 at 17:39
Ya Its getting Segfault. – Neel Basu Aug 27 '10 at 18:39
show 1 more comment
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.