2

How can I pass a value of an array by reference to modify its value inside an object? I've tried it with the & operator at public function f(&$z) {.

<?php
    class C {
        private $a;

        public function f($z) {
            foreach ($z as $i => $v) {
                $v = 8888;
            }
        }
    }

    $p = 4;
    $obj = new C();
    $obj->f(array('key'=>$p));
    echo $p;
?>

I would like to set the 8888 value to the $p variable.

The fiddle: http://codepad.org/RvKU4hY1

3
  • use public function f(&$z) definition Commented Apr 11, 2014 at 16:30
  • @vp_arth When I do this, I just get an error: Fatal error: Cannot pass parameter 1 by reference Commented Apr 11, 2014 at 16:32
  • Because you provide generic array, see my answer Commented Apr 11, 2014 at 16:35

3 Answers 3

2

You have to use references when you 1) create the array, 2) iterate over it:

<?php
  class C {
    private $a;

    public function f($z) { 
        foreach ($z as $i => &$v) {
            $v = 8888;
        }
    }
  }
    $p = 4;
    $obj = new C();
    $obj->f(array('key'=>&$p));
    echo $p;
?>
Sign up to request clarification or add additional context in comments.

1 Comment

@felipe.zkn: please see the edit - you actually only need two of them.
2

Only slightly different to georg, you can do it this way;

<?php
class C {
    private $a;

    public function f($z) {
        foreach ($z as $i => $v) {
            $z[$i] = 8888;
        }
    }
}
$p = 4;
$obj = new C();
$result = array('key'=> &$p);
$obj->f($result);

echo $p;
?>

Comments

2

Here the code with explanation:

<?php
    class C {
        private $a;

        public function f(&$z) { // we receive a pointer
            foreach ($z as $i => $v) {
                //  here you overwrite $v, even if it a pointer in foreach
                // It has mean when you want to do unset($v); here
                // $v = 8888;
                $z[$i] = 8888;
            }
        }
    }

    $p = 4;
    $obj = new C();
    $param = array('key'=>$p);
    $obj->f($param);
    echo $p;

Comments

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.