Accessing variables from within a function within a class (scopes?)

146 views Asked by At

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?

3

There are 3 answers

5
Saul On BEST ANSWER

$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.

0
Kevin Read On
function doSomething() {
  global $myvar;
  echo "myvar: $myvar";  
}  
0
meze On

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);