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?
LVL 1
rgb192Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Mark BradyPrincipal Data EngineerCommented:
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.
0
Ray PaseurCommented:
Please see the answer here:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28229102.html#a39460164

This is pretty good, too.
http://www.php.net/manual/en/language.oop5.references.php#101900

Install this and run it to see the effect.
<?php // RAY_temp_rgb192.php
error_reporting(E_ALL);
echo '<pre>';

// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28229122.html

// PARALLEL CONSTRUCTION OF AN ARRAY AND OBJECT
$arr = array();
$arr['abc'] = 'ABC';
$arr['def'] = 'DEF';
$arr['ghi'] = 'GHI';

$obj = new stdClass;
$obj->abc = 'ABC';
$obj->def = 'DEF';
$obj->ghi = 'GHI';

// SHOW THE ARRAY AND THE OBJECT
var_dump($arr);
var_dump($obj);

//  FUNCTION WILL BE CALLED TO ITERATE OVER EACH DATA CONSTRUCT
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);
        }
    }
}

work($arr);
work($obj);

// SHOW HOW THE EFFECT OF UNSET MUTATED THE OBJECT, BUT NOT THE ARRAY
var_dump($arr);
var_dump($obj);

// TRY IT AGAIN USING THE "AMPERSAND" NOTATION
work(& $arr);
var_dump($arr);

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
rgb192Author Commented:
>>
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
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Mark BradyPrincipal Data EngineerCommented:
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
0
Ray PaseurCommented:
An object is created and loaded with properties on line 13-16 of the code example here:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28229122.html#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.
0
Mark BradyPrincipal Data EngineerCommented:
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
0
rgb192Author Commented:
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);
0
rgb192Author Commented:
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
0
Mark BradyPrincipal Data EngineerCommented:
I think you are perhaps over thinking this issue. Passing anything in by reference (if it is a variable...preceded by a $ sign) simply means the function/method you pass it to can modify it instead of modify a copy of it which is what happens when you pass it in as an argument without the &.
0
rgb192Author Commented:
I learned from the example and the explanation that '&' modifies the function/method
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.