Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3

Thread: & symbols

  1. #1
    Senior Coder missing-score's Avatar
    Join Date
    Jan 2003
    Location
    UK
    Posts
    2,194
    Thanks
    0
    Thanked 0 Times in 0 Posts

    & symbols

    ok, ive seen code examples like:

    PHP Code:

    $var 
    = &new class(); 
    what does the & do? ive seen it used other places too... i looked on php.net, but couldnt find anything via search.

  • #2
    Senior Coder
    Join Date
    Jun 2002
    Location
    frankfurt, german banana republic
    Posts
    1,848
    Thanks
    0
    Thanked 0 Times in 0 Posts
    The "&" symbol is used to assign a reference to the variable, instead of a copy. Here's a sample that illustrate the underlying problem:

    PHP Code:
    class Book {
        var 
    $_author '';
        
        function 
    Book($author) {
            
    $this->_author = (string) $author;    
        }
        
        function 
    getAuthor() {
            return 
    $this->_author;
        }
        
        function 
    setAuthor($author) {
            
    $this->_author = (string) $author;
        }
    }

    $redBook = new Book('Bob');
    var_dump($redBook->getAuthor());

    $blueBook $redBook;
    $blueBook->setAuthor('Joe');

    var_dump($redBook->getAuthor()); 
    The first dump prints "Bob", as expected. But what prints the second dump? It's exactly the same statement, only that some lines before we assigned $redBook to $blueBook, and change the author of $blueBook. But $blueBook is the same as $redBook, so shouldn't that change the author of $redBook underneatch, because they all refer to the same object? Nope. PHP has a very nasty characterisc of creating copies of objects when they are assigned to another variable. So the last dump prints "Bob" again, because the change to the book's author was made on a copy of the object, not the object itself.

    But most of the time you rather want a reference, and that's why there is this & symbol to force the assignment of a reference. You can read more about references in PHP here:
    http://www.php.net/manual/en/language.references.php
    De gustibus non est disputandum.

  • #3
    Senior Coder missing-score's Avatar
    Join Date
    Jan 2003
    Location
    UK
    Posts
    2,194
    Thanks
    0
    Thanked 0 Times in 0 Posts
    i see , thanks


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •