0

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

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

3 Comments

> 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 ?
@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?
@user Can you post a small script that reproduces the problem and post it somewhere (e.g. pastebin)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.