【问题标题】:PHP included variable scopePHP包含变量范围
【发布时间】:2013-06-05 19:16:43
【问题描述】:

所以我有 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 中的回显工作正常 但是,在测试类中,变量返回一个通知:未定义变量: 我尝试将 $var 更改为全局变量,但这似乎没有帮助。我想我没有正确理解 PHP 中包含的文件的范围。任何人都可以帮助我,以便我可以在课堂上使用 $var 吗?

谢谢

【问题讨论】:

  • 在构造函数中设置global 会有所帮助,但将$var 传递到__construct() 中会更好,如public function __construct($var){}

标签: php oop include scope


【解决方案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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    • 2010-12-19
    相关资源
    最近更新 更多