所以我有3个文件
file1.php
$var = "string";
file2.php
include(file1.php);
include(file3.php);
echo $var;
$test = new test();
file3.php
class test
{
public function __construct()
{
if($var = "string")
{
// do things
}
}
}
现在,文件2中的echo工作正常 但是,在Test Class中,变量返回一个Notice:Undefined变量: 我已经尝试将$ var更改为全局,但这似乎没有帮助。我想我不能正确理解包含文件的PHP范围。任何人都可以帮助我,所以我可以在课堂上使用$ var吗?
由于
答案 0 :(得分:1)
有两种方法可以做到这一点
错误的方式
class test
{
public function __construct()
{
global $var;
if($var == "string")
{
// do things
}
}
}
这会将var导入构造函数范围,但违反了面向对象编程的最大好处,即封装功能。
这是正确的方法
class test
{
public function __construct($var)
{
if($var == "string")
{
// do things
}
}
}
$test = new test($var);