SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Guru
    Join Date
    Nov 2004
    Location
    Plano
    Posts
    643
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    using references within objects

    so i want to have a $session variable throughout my entire website, i also want to be able to edit the $session variable from anywhere, and have it update the location it references, not a copy.

    is this correct?

    PHP Code:
    $session = new Session();

    class 
    User {
       var 
    $id;
       var 
    $session;

       function 
    __construct(&$session){
          
    $this->session =& $session;
       }

       function 
    otherFunction(){
          
    $this->session->user 'Tommy';
       }

    in that example, does otherFunction edit the global session variable, or just a copy of it (local within the User class). if it's not working how i expect it to...how do i get it to work as expected?

    thanks.

  2. #2
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In php5 you there's no need anymore to use references with objects. Just remove all '&' to get working php5 code.

  3. #3
    SitePoint Guru
    Join Date
    Nov 2004
    Location
    Plano
    Posts
    643
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    thanks for your reply, stereofrog

    i am also wondering, if i don't want to pass in $session as an arguement to the constructor, but instead call it from its global status, would that also not need to use the explicit reference syntax?

    i.e.

    PHP Code:
    $session = new Session();

    class 
    User {
       var 
    $id;
       var 
    $session;

       function 
    __construct(){
          
    $this->session $_GLOBAL['session'];
       }

       function 
    otherFunction(){
          
    $this->session->setAge(15);
       }
    }

    $user = new User(); 
    would that work as expected? and by working as expected i mean the global $session now points to the same location that $user->session; points to?

    thanks for your time,
    blayne

  4. #4
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes, in php5 global $session and $user->session are referring to the same object. The reason is that unlike previous version, in php5 an object variable holds the pointer (address) of the object, not the object itself.

  5. #5
    SitePoint Guru
    Join Date
    Nov 2004
    Location
    Plano
    Posts
    643
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    i get it now, thanks!


Bookmarks

Posting Permissions

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