Search code examples
phpbyref

With PHP does assigning a byref var to another var assign the reference or copy the value?


Take, as an example, this abstract class from a project I am working on. (minus all the really interesting bits).

abstract class col_meta extends meta {

    protected $col_obj;

    public function inject_object(&$obj);

    public function &get_object(){
        return $this->col_obj;
    }
}

I understand that the inject_object method receives $obj as a reference but if I want the class to assign it to a protected variable do I need to assign by reference again?

like this:

class foo extends col_meta {

    public function inject_object(&$obj){
        $this->col_obj = &$obj;
    }

}

Or, having only been given a reference, do I need to simply copy the reference into the protected variable?

class bar extends col_meta {

    public function inject_object(&$obj){
        $this->col_obj = $obj;
    }

}

I've been tying my mind up in knots trying to work this out as they both seem right.


Solution

  • By definition, by reference is "by reference"; meaning that if the value is changed in the function, it's changed in the calling script.

    However - because it provides better performance - if you pass "by value", PHP still passes the reference to the function, but creates a copy (by value) if you change the value in the function.

    Note that objects are always effectively "pass by reference", because your object variable is actually a pointer to the object, so any changes to an object inside the function will be reflected outside the function as well.

    Don't pass by reference unless you explicitly want a variable changed inside the function to be changed outside the function as well.

    If you want a "copy" of the object inside you class, rather than the reference; then use clone to create a copy.