Re: Is this a bug?!!! I cna't believe! Sorry, if im wrong...

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



> No
>
> news.php.net wrote:
>> <?
>>
>>  class A
>>  {
>>   var $name;
>>   function A($str)
>>   {
>>    $this->name = $str;
>>   }
>>  }
>>
>>  $arr = array();
>>
>> //Put to array to objects of class A,
>> // where their attribute A::a is assigned a different value
>> //objects are assigned to an array by reference
>>
>> $a = &new A("qaz");
>>  $arr[0] = &$a;
>
> $arr[0] and $a reference now the same variable
>
>>
>>  $a = &new A("wsx");
>
> by changing $a you also changed $arr[0]

No. referencs are not pointers! Here in "  $a = &new A("wsx") " I assign $a
by reference, and now $a references the different location, and $arr[0]
references the same. Assigning $a by references doesnt affect $arr[0],
though the pointed to the same location before...
After all this is the prove:

This is my  previous assignment code:


 class A
 {
  var $name;
  function A($str)
  {
   $this->name = $str;
  }
 }

 $arr = array();

//Put to array to objects of class A,
// where their attribute A::a is assigned a different value
//objects are assigned to an array by reference

$a = &new A("qaz");
 $arr[0] = &$a;

 $a = &new A("wsx");
 $arr[1] = &$a;

//HERE IS THE PROVE
print_r($arr);
//Watch the OUTPUT... there are DIFFERENT objects laying in the array! This
is the point of my question...

// But if you do this:

 foreach($arr as $a)
 {
  echo "(".$a->name.")";
 }

// You see that iterating the objects it somehow references the same
object...
// or the same 'name' attrribute of the first object in the array...











>
>>  $arr[1] = &$a;
>
> now $a, $arr[0] and $arr[1] reference the same variable, they just have 
> different names.
>
> More:
> http://sk.php.net/manual/en/language.variables.php
> http://sk.php.net/manual/en/language.references.php
>
>>
>>
>> //But watch the output!!!
>> // It is "(qaz)(qaz)", which means that the attribute of a first
>> // object assigned to array is outputted!!! WHY?!?!!!
>>  foreach($arr as $a)
>>  {
>>   echo "(".$a->name.")";
>>  }
>> ?>
>>

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux