Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Copying Objects

From PHP 5 onward, objects are always handled as references. This means that when you pass an object into a function, any changes you make to it in there are reflected outside the function. For example:

    function namechange($dog) {
            $dog->Name = 'Dozer';
    }

    namechange($poppy);
    print $poppy->Name . "\n";

Here we define a function that accepts one variable, $dog, then changes its name to Dozer. We then pass our $poppy dog into the function, and output its name—unsurprisingly, it outputs "Dozer" rather than "Poppy". Sometimes it is important to only work on copies of objects, particularly if you don't want to affect the state of the original. To do this, we use the built-in keyword clone, which performs a complete copy of the object. For example, we could use the namechange() function above like this:

    namechange(clone $poppy);

That would create a copy of $poppy and pass it into namechange(), leaving the original $poppy untouched. Here is the output of the code now:

    Creating Poppy
    Creating a poodle
    My name is Poppy. If you find me, please call 555-1234
    Dozer is no more...
    Poppy
    Poppy is no more...

Note that Dozer is still mentioned—that is because the copied object passed into namechange() gets its name changed to Dozer; then, when the function ends, the copied object is automatically destroyed by PHP, and its destructor is called. However, $poppy lives on untouched, as you can see from the last two lines.

Internally, the clone keyword copies all the properties from the first ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page