php类返回; 功能回归

object var $c->$var1 has been changed in class a;

var $new_var has not be changed in function d; i was a litte puzzled. my english is poor,can you understand me?

<?php
    class a{
        public function test () {
            $b = new b;
            $c = new c;
            $b->test($c);
            var_dump($c);
        } 
    }

    class b{
        public function test($c) {
            $c->var1 = 2;
            return $c;
        }
    }

    class c {
        public $var1 = 1;
    }

    $a = new a;
    $a->test();

    function d($new_var) {
        $new_var = 2;
        return $new_var;
    }

    $new_var = 1;
    d($new_var);
    echo $new_var

You problem is that you have this function

function d($new_var) {
        $new_var = 2;
        return $new_var;
}

Where is it true that you maybe pass a different variable as parameter, but then you take that parameter and you decide to set it = 2 and then return it. If you want to return what you passed you should change it in

function d($new_var) {
        return $new_var;
}

Or if you want something similar to test function of class b try tgus

function d($new_var) {
    $d->new_var = $new_var;
    return $d;
}

So you can access to your $new_var in the returned objecd $d

You expect the following piece of code to change the value for $new_var from 1 to 2, right?

$new_var = 1;
d($new_var);
echo $new_var

Alas, that cannot be, because the returned value is never assigned back to the variable. To make sure the passed variable will retain its new value even outside the scope of the function it was passed to as an argument, you need to pass the variable as a reference instead of as a value, like this:

function d(&$new_var) {
    $new_var = 2;
    return $new_var;
}

Notice the ampersand (&) in front of the variable name in the signature of the function. This will cause the variable to be passed as a reference, so that it will retain any changes made to it inside the function.