global scope in a Class

Discussion in 'PHP' started by benjib98, Dec 18, 2007.

  1. #1
    Hi guys,

    Just started learning PHP (I already have some experience with other OOP languages) and got to a point where I am a bit confused.
    It is a global keyword(?), which I am confused about.I understand thta in php there are function scopes, so variables in a function are in local scope and variables outside the function are "global" variables which are accessible through the global keyword(?).
    Is the code below correct than:
    <? php
    public class TestClass
    {
    private $_var = 'global variable';

    function Display1()
    {
    global $_var;
    echo $_var;
    }
    //or can I use this way too?
    function Display2()
    {
    echo $this->_var;
    }
    }
    ?>

    Thanks for any clarification.
    Ben
     
    benjib98, Dec 18, 2007 IP
  2. InFloW

    InFloW Peon

    Messages:
    1,488
    Likes Received:
    39
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Seems you're a little confused here

    $_var was declared within the class so it's owned by the class and is not actually of global scope. So you may reference it using $this->_var within an function in the class

    This would change if you had $myglobalvar = 5; outside of the class then wanted to access it. In that case you'd need to use the global keyword.

    Of course globals are frowned upon so if you needed the var it's always best to pass it as a parameter opposed to saying global in the function.
     
    InFloW, Dec 18, 2007 IP
  3. benjib98

    benjib98 Peon

    Messages:
    23
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Hi InFloW,

    Thank you for your clarification, as I said I am newbie in PHP and got the global stuff wrongly.
    Cheers

    Ben
     
    benjib98, Dec 18, 2007 IP