Link to home
Start Free TrialLog in
Avatar of rgb192
rgb192Flag for United States of America

asked on

real world example of object oriented references

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

Describe how this could be used in a program?
What is the purpose of this?

Any actual examples to explain why a reference?
Avatar of Mark Brady
Mark Brady
Flag of United States of America image

The purpose of passing an object or variable as a reference instead of as an argument is so the function you are passing it to can modify it. Here is a very simple example.

<?php
class Test {


public function run() {
     $my_array = array('cat', 'dog');
      var_dump($my_array);

  // run this private function to add a bird to the array
    $this->add_animal($my_array, 'bird');

    var_dump($my_array);
}

private function add_animal(&$array, $animal) {
     array_push($array, $animal);
}

}

?>

Open in new window


Notice the private function does not need to return anything as it is only modifying the array sent to it. This is passing by reference (preceeding the arguemant with an '&')

That is a very quick and simple example.

If you did not pass it in by reference but still wanted to modify a variable you can make it global like this.

$this->name = 'Mark';

Now you can modify this value from anywhere inside your class.
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rgb192

ASKER

>>
The purpose of passing an object or variable as a reference instead of as an argument is so the function you are passing it to can modify it.

which function?

Do you mean the private method in the class?

maybe can you include how to create the object
Yes the private method inside the class. It is the same as making a variable global inside of a standard php function so you can manipulate it.

To instantiate the class I gave as an example you would do this.
Save the sample code as 'my_sample_code.php' and in the same folder Create a new php script and add the following

<?php
include_once 'my_test_code.php'; // this is my sample code above in a file

$test = new Test();
// run it
$test->run();

?>

Open in new window


Save this file as something (whatever you want) .php

When you navigate your browser to you newly saved file you will see the result
An object is created and loaded with properties on line 13-16 of the code example here:
https://www.experts-exchange.com/questions/28229122/real-world-example-of-object-oriented-references.html?anchorAnswerId=39460265#a39460265

The array is passed to the function work() by copy.  The object is passed by reference.  For better or worse, that is how PHP works.  Since the array that is passed into the function is a copy, the mutations we make to the array are made in the copied array inside the function, not to the array that exists in the variable scope outside the function.  Since the object is passed by reference, the statements inside the function refer to the original object.

On line 44 of the code example, it shows how to pass a non-object variable by reference.  If you install the script and run it, you can watch the code and output together to see what happens.
I think the example you have provided Ray is a little muddy for a beginner. Perhaps modifying the function "work()" to this

function work(&$thing)
{
    foreach ($thing as $key => $val)
    {
        if ($key == 'def')
        {
            // REMOVE SOMETHING FROM THE DATA
            if (is_array($thing))  unset($thing[$key]);
            if (is_object($thing)) unset($thing->$key);
        }
    }
}

Open in new window


is clearer. Now no matter what you pass into it (array or object) it will modify the original.

I guess what we are trying to get across here is a variable created inside a class can not be modified inside a class method (function) unless it follows one of these conditions.

1: Inside the function that variable is made global (this is old school but still used)
     ex:  global $my_variable;

2: The variable is set as global by creating it using the 'this' keyword
     ex:  $this->my_variable = 'Mark';

3: You pass it into a function by reference. In the function () parameters you preceed the variable name with a '&'.
   ex:  function test(&$data) {}
Now $data can be anything. It can be an array, an object or a simple value of any kind.
The important thing to note here is that if you precede it with an & then whatever you pass that function can be modified inside the function which modifies the original variable.

In practice I prefer to use the $this-> keyword so I don't need to worry about passing in by reference of making them global inside a function. This is only done for items that you need a function to modify directly.

For most practices you send data into a function and it performs whatever operations are required and sends back a result. Usually that result is assigned to a variable at that time.

Good luck with your learning
Avatar of rgb192

ASKER

So Ray's outputs:

array(3) {
  ["abc"]=>
  string(3) "ABC"
  ["def"]=>
  string(3) "DEF"
  ["ghi"]=>
  string(3) "GHI"
}
object(stdClass)#1 (3) {
  ["abc"]=>
  string(3) "ABC"
  ["def"]=>
  string(3) "DEF"
  ["ghi"]=>
  string(3) "GHI"
}
array(3) {
  ["abc"]=>
  string(3) "ABC"
  ["def"]=>
  string(3) "DEF"
  ["ghi"]=>
  string(3) "GHI"
}
object(stdClass)#1 (2) {
  ["abc"]=>
  string(3) "ABC"
  ["ghi"]=>
  string(3) "GHI"
}
array(2) {
  ["abc"]=>
  string(3) "ABC"
  ["ghi"]=>
  string(3) "GHI"
}





and
Elvin66 '&' modification:

array(3) {
  ["abc"]=>
  string(3) "ABC"
  ["def"]=>
  string(3) "DEF"
  ["ghi"]=>
  string(3) "GHI"
}
object(stdClass)#1 (3) {
  ["abc"]=>
  string(3) "ABC"
  ["def"]=>
  string(3) "DEF"
  ["ghi"]=>
  string(3) "GHI"
}
array(2) {
  ["abc"]=>
  string(3) "ABC"
  ["ghi"]=>
  string(3) "GHI"
}
object(stdClass)#1 (2) {
  ["abc"]=>
  string(3) "ABC"
  ["ghi"]=>
  string(3) "GHI"
}
array(2) {
  ["abc"]=>
  string(3) "ABC"
  ["ghi"]=>
  string(3) "GHI"
}


Why is this the only call that got changed by '&'
// SHOW HOW THE EFFECT OF UNSET MUTATED THE OBJECT, BUT NOT THE ARRAY
var_dump($arr);
Avatar of rgb192

ASKER

The array is passed to the function work() by copy.  The object is passed by reference.  For better or worse, that is how PHP works.  Since the array that is passed into the function is a copy, the mutations we make to the array are made in the copied array inside the function, not to the array that exists in the variable scope outside the function.  Since the object is passed by reference, the statements inside the function refer to the original object.


and with the
Elvin66 '&' modification:
is the &$thing a reference of the array
is the &$thing a reference of the object
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rgb192

ASKER

I learned from the example and the explanation that '&' modifies the function/method