3

I need to access some variables of an external php file in most of functions of a class. I'm accessing in following way (and it works fine)

class test{

function a(){ 
    global $myglobalvar ;
    ..
    ..
    }

function b(){ 
    global $myglobalvar ;
    ..
    ..
    }

function c(){ 
    global $myglobalvar ;
    ..
    ..
    }

}

Is there a way that i can access $myglobalvar in all functions of the class without declaring in each function? I did read that it can be done by declaring only once in the constructor of the class, but I dont know how to do it. Thanks for any help.

3
  • 7
    That's PHP's way of telling you "stop this shit, you're doing it wrong(tm)". And mind you, PHP isn't one of those languages fanatic about good code. Commented Mar 6, 2011 at 18:41
  • 1
    @delnan: +1 for the first part -2 for the second. Commented Mar 6, 2011 at 19:30
  • make that variables in object level Commented Mar 10, 2016 at 3:55

3 Answers 3

14
class test{

 private $myglobalvar;

 public function __construct($var){
  $this->myglobalvar = $var;
 }

 function a(){ 
  echo $this->myglobalvar;
 }

 function b(){ 
  echo $this->myglobalvar; 
 }

 function c(){ 
  echo $this->myglobalvar;
 }

}

$test = new test("something");
$test->a(); // echos something
$test->b(); // echos something
$test->c(); // echos something
Sign up to request clarification or add additional context in comments.

2 Comments

You are missing the global declaration
@RDL the whole point of this design is that the global is passed via the constructor so that the object's scope is properly insulated and isn't dependent on a specific naming of an external resource. Promotes reuse.
5

You can create a reference to a global variable in the constructor (much like global would):

class test{

    function __construct() { 
        $this->myglobalvar = & $GLOBALS["myglobalvar"];

Which then allows aceess to the global via $this->myglobalvar in each method.

1 Comment

Sure that would work, but why teach people code smells like that?
2

If you tell us more about this case, we might be able to tell you a better way to solve your problem. Globals should be avoided, whenever possible. Are you really talking about a variable or is it more like a configuration option that stays the same during a whole server roundtrip. In that case you could think of treating it like a configuration option and store it in a registry object (singleton).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.