1

I'm fairly new with classes, and I've been looking online for some kind of tutorial on this, but unfortunately I've been unsuccessful at finding a solution. Any help you guys could give me would be much appreciated.

I have 2 files.

1) variables.inc.php:

$myvar = "hello world";

2) myclass.php:

include("variables.inc.php");
class myClass {

    function doSomething() {
        echo "myvar: $myvar";
    }
}

The problem: $myvar returns empty. I tried adding this line between function doSomething() { and echo...: global $myvar; But it doesn't seem to work that way either. Any suggestions?

Devendra D. Chavan
  • 8,871
  • 4
  • 31
  • 35
Jay
  • 1,084
  • 4
  • 18
  • 43

3 Answers3

2

$myvar is defined in global scope.

If it really needs to be accessed then

function doSomething() { global $myvar; echo "myvar: $myvar"; }

However the usage of global variables in other scopes is considered bad practice.

See Variable scope chapter in the official PHP manual for a more detailed explanation.

Saul
  • 17,973
  • 8
  • 64
  • 88
  • Why would it be considered bad practice? – Jay Feb 06 '11 at 17:16
  • @Jay: [Try this](http://stackoverflow.com/search?q=global+variable+practice), or one of my [own answer also explains why](http://stackoverflow.com/questions/4696189/set-a-php-object-global/4696288#4696288). – netcoder Feb 06 '11 at 17:23
  • if you know it's a bad practice, why suggest it? ;s – meze Feb 06 '11 at 17:36
  • @meze: I suggest not to use globals. The code is provided as an explanation on how globals work. – Saul Feb 06 '11 at 17:51
  • @Jay: Mainly because one purpose of classes and functions is to encapsulate variables into a code region where they are declared. That is done in order to facilitate automatic memory management and to reduce the risk of accidentally reusing an existing variable elsewhere. Going with global pretty much defeats those aims. – Saul Feb 06 '11 at 17:51
2
function doSomething() {
  global $myvar;
  echo "myvar: $myvar";  
}  
Kevin Read
  • 2,173
  • 16
  • 23
0

NEVER use global with classes!

If you need a variable in your class, then inject it in a method or the constructor:

class myClass {

function doSomething($myvar) { echo "myvar: $myvar"; }

}

$obj = new myClass;
$obj->doSomething($myvar);
meze
  • 14,975
  • 4
  • 47
  • 52