PHP Classes and Objects Assigning Object References - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Classes and Objects Assigning Object References - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Saturday, May 25, 2019

PHP Classes and Objects Assigning Object References

PHP Classes and Objects




Assigning Object References

Problem

You want to link two objects, so when you update one, you also update the other.

Solution

Use = to assign one object to another by reference:

            $adam = new user;
            $dave = $adam;

Discussion

When you do an object assignment using =, you don’t create a new copy of an object, but a reference to the first. So, modifying one alters the other.

This is different from how PHP treats other types of variables, where it does a copy-by-value:

            $adam = new user;
            $adam->load_info('adam');

            $dave = $adam;

Now $dave and $adam are two names for the exact same object.



No comments:

Post a Comment

Post Top Ad