0

Possible Duplicate:
[PHP] global in functions

Is it bad programming (PHP) practice to access a global variable in a function inside a class in following way?

class test{

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

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

}

Thanks.

Community
  • 1
  • 1
Jay
  • 9,641
  • 8
  • 22
  • 33

5 Answers5

3

In my opinion it is. You can always "publish" your global variable to your methods with the constructor and keeping a link through a field.

Nick Weaver
  • 46,888
  • 12
  • 96
  • 106
2

In my point of view, yes its not a good practice to use like as you did. You can use this as

class test{
  private $myVar;
  function __construct($myVar)
  {
    $this->myVar = $myVar;
  }
  function a(){
   echo $this->myvar;
   ..
  }
}




class test{
      private $myVar;
      function __construct()
      {
        global $myVar;
        $this->myVar = $myVar;
      }
      function a(){
       echo $this->myvar;
       ..
      }
    }
Gaurav
  • 26,880
  • 8
  • 47
  • 76
1

It is not elegant. You should pass that var inside the constructor and save it into a private $var inside the class to be used in every function with an easy $this->var.

$myUnicorn = "Pink";
class Unicorn {
    private $currentUnicorn;

    public function __construct($current) {
        $this->currentUnicorn = $current;
    }

    public function echoIt() {
        echo $this->currentUnicorn;
    }

    public function killIt() {
        unset($this->currentUnicorn); // :(
    }
}

$u = new Unicorn($myUnicorn);
$u->killIt(); 
Shoe
  • 70,092
  • 30
  • 150
  • 251
0

You shouldn't be doing something like that unless you positively have to. If there is a better way to do it that makes sense, then use it. For example, some people use that to access config variables, but a better way would be to use define() statements or a static class and a file.

TL;DR - Only do it if you must. Otherwise, don't.

JohnP
  • 47,501
  • 10
  • 101
  • 134
0

IMO it is super bad. You make your class depended on an external variable. Objects instantiated in a context where this variable does not exist won't work.

Pass the variable to the constructor of the class. This way, an object can only be instantiated if the parameter is provided.

Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072