Search code examples
phpclassfunctionvariablesscopes

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


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?


Solution

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