Question

While practicing for certification, I came across one MCQ the question. It was as below.

Q: Consider the following script. What will it output?

<?php
$global_obj = null;
class my_class
{
   var $value;
   function my_class()
   {
      global $global_obj;
      $global_obj = &$this;
   }
}
$a = new my_class;
$a->my_value = 5;
$global_obj->my_value = 10;
echo $a->my_value;
?>

Choose Right One Options:

  • A. 5
  • B. 10
  • C. Nothing
  • D. The constructor will throw an error
  • E. 510

I chose and B: 10 as because in my_class constructor $global_obj is being initialized by the reference of $this. By when I cross checked my answer was wrong

As a description they mentioned that

This is a really tricky one. Upon first examination, it would seem that the constructor of my_class stores a reference to itself inside the $global_obj variable. Therefore, one would expect that, when we later change the value of $global_obj->my_value to 10, the corresponding value in $a would change as well. Unfortunately, the new operator does not return a reference, but a copy of the newly created object. Therefore, the script will output 5 and the correct answer is A.


Ya I agree the description is well enough but still I am not able to digest it as because we have clearly assigned $global_obj the reference of $this then how can be this possible? Can any one please explain in detail?

Was it helpful?

Solution

we have clearly assigned $global_obj the reference of $this then how can be this possible?

You assign the global variable within the constructor. At that time, you are referencing kind of a temporary object. Then the constructor returns a copy of that temporary object. This is that copy that $a will reference (whereas the global var still references the temporary object).

Going OOP with php 4 is nuts. I guess you should not understand the OOP behaviour of PHP 4 but just accept it...

OTHER TIPS

this script will output "5" which would be A along with the following warning Warning: Creating default object from empty value

the reason for this is when you set this

                 `$global_obj = &$this;`

what your assigning is reference to the current object

this article may help

http://www.webmaster-source.com/2010/02/25/why-do-some-php-variables-have-an-ampersand-before-them/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top