1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

How can I make a class variable global for other classes

Discussion in 'PHP' started by peanutpad, Sep 28, 2007.

  1. #1
    Here's my problem.
    I wrote a class that gets all the logged in users information it goes a little something like this

    <?php
    class user {
          var $username = "";
    
          function user() {
               $this->set_user_info();
          }
    
          function set_user_info(){
                $this->username = "myusername";
          }
    }
    
    $user_obj = new user();
    
    ?>
    Code (markup):
    What I would like to be able to do.

    I have about 6 other classes that all do different things but are all dependent on the user class variables.
    Example

    class email {
        
         function send_email() {
               $to = "to@to.com";
               $from = "from@from.com"
               $message = "this email was sent by $user_obj->username";
               mail(.........
         }
    }
    Code (markup):
    What I would like to know is, how can I make the variables from the user class accessible to all my classes. What would be the best way. Right now I am calling global $user_obj; in all the functions that use the user class variables.
    Would it be better to make the other classes extend the user class or is there an easier method for this that I am unaware of! Thanks
     
    peanutpad, Sep 28, 2007 IP
  2. petronel

    petronel Peon

    Messages:
    113
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #2
    you can try
    
    class email {
    
         global $user_obj;
    
         function send_email() {
               $to = "to@to.com";
               $from = "from@from.com"
               $message = "this email was sent by $user_obj->username";
               mail(.........
         }
    }
    
    PHP:
     
    petronel, Sep 28, 2007 IP
  3. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #3
    nico_swd, Sep 28, 2007 IP
  4. msaqibansari

    msaqibansari Peon

    Messages:
    84
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #4
    both coding style is workable....
     
    msaqibansari, Sep 28, 2007 IP