开发者

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

开发者 https://www.devze.com 2023-02-09 02:06 出处:网络
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

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?


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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消