Nick
Nick

Reputation: 906

php passing an object back from a class function

I have a set of PHP functions that I want to move into a new class. One of the functions is using &$obj in an argument to modify the original object:

function process_new_place_names(&$obj)

any changes made to $obj in this function are passed back to the script.

Question is, can I do this inside a PHP class too? Also, what is the terminology of this approach?

Upvotes: 1

Views: 152

Answers (2)

Will Vousden
Will Vousden

Reputation: 33358

As SomeKittens says, this is perfectly possible inside a class. However, if $obj is itself an instance of a class, and all you need to do is modify its member variables (known as mutating the object) then there's no need to pass it by reference.

For example, the following code will output baz;

class Foo
{
    public $bar;
}

function process_new_place_names($obj)
{
    $obj->bar = 'baz';
}

$obj = new Foo();
$obj->bar = 'bar';
process_new_place_names($obj);
echo $obj->bar;

Pass-by-reference is only necessary when you want to change the value of the variable itself; for example, re-assigning the object reference:

function process_new_place_names(&$obj)
{
    $obj = new Foo();
    $obj->bar = 'baz';
}

Upvotes: 2

SomeKittens
SomeKittens

Reputation: 39532

You can absolutely do this inside of classes. It's known as passing by reference.

Further reading:

http://php.net/manual/en/language.references.php http://php.net/manual/en/language.oop5.references.php

Upvotes: 3

Related Questions