|
Posted by Jason Barnett on 01/06/05 23:28
Don wrote:
> Hi,
>
> Reading the PHP 5 documentation at: HYPERLINK
> "http://www.php.net/manual/en/language.oop5.basic.php"http://www.php.net/man
> ual/en/language.oop5.basic.php, I am confused.
>
> In the example given, what is the difference between:
> $assigned = $instance;
> $reference =& $instance;
>
> I would expect all of the var_dump to display NULL
>
> The doc says "When assigning an already created instance of an object to a
> new variable, the new variable will access the same instance as the object
> that was assigned." so the above assignments seem the same to me and setting
> $instance to NULL should also set $assigned to NULL.
>
Correct. Given only these assignments, $instance is NULL and so
$assigned and $reference would also be NULL.
> If this is not the case and not using the '&' specifies a 'copy'
> (contradicting the documentation) then what's the purpose of object cloning?
>
This was pretty much only needed in PHP4. It might help you to read the
PHP4 OOP documentation notes. In PHP5 you don't need the & to signify
an object as a reference; references are passed by default instead of
copies.
http://php.net/manual/en/language.oop.php
> I tried the code below and find that it gives the exact same output
> regardless if I am using the '&' or not so it seems to assign be reference
> either way.
>
> <?php
> class SimpleClass
> {
> // member declaration
> public $var = 'a default value';
>
> // method declaration
> public function displayVar() {
> echo $this->var;
> }
> }
>
> $instance = new SimpleClass();
> $assigned = $instance;
> // $assigned = &$instance; // No difference if this line is used instead
In PHP5, the above comment is true. In PHP4, it is not true.
>
> $instance->var = 'Value has been changed';
>
> var_dump($instance);
PHP4: 'Value has been changed'
PHP5: 'Value has been changed'
> echo '<br /><br />';
> var_dump($assigned);
PHP4: 'a default value' (if you use the &, this would read 'Value has
been changed')
PHP5: 'Value has been changed'
> ?>
>
>
>
--
Teach a person to fish...
Ask smart questions: http://www.catb.org/~esr/faqs/smart-questions.html
PHP Manual: http://php.net/manual/
php-general archives: http://marc.theaimsgroup.com/?l=php-general&w=2
Navigation:
[Reply to this message]
|