【问题标题】:Global variable in object created from another object从另一个对象创建的对象中的全局变量
【发布时间】:2015-08-04 11:28:09
【问题描述】:

有两个类,每个类都在自己的文件中:

<?php
namespace test;

class calledClass {
    private $Variable;

    function __construct() {
        global $testVar;
        require_once 'config.php';
        $this->Variable = $testVar;
        echo "test var: ".$this->Variable;        
    }
}
?>

<?php
namespace test;

class callingClass {
    function __construct() {                
        require_once 'config.php';
        require_once 'calledClass.php';
        new calledClass();
    }
}

new callingClass();
?>

和简单的config.php:

<?php
namespace test;
$testVar = 'there is a test content';
?>

当我启动callingClass.php(创建对象calledClass)时,calledClass 中的属性$Variable 为空。但是当我手动启动calledClass.php 时,它会从config.php 读取含义$testVar,并将其假定为$Variable

如果我在 callingClass 中将 $testVar 声明为 global,这会有所帮助 - calledClass 可以从 config.php 读取 $testVar

谁能告诉我为什么从另一个对象创建的对象不能将变量声明为全局变量并使用它们?

【问题讨论】:

  • 除此之外,这将是非常糟糕的做法,而且不是 OOP,而且您正在做的还有无数其他问题; $testVar 在调用类构造函数中不是全局的,只是该方法中的局部范围变量
  • 谢谢。在类中使用配置文件的更好方法是什么(除了将变量作为函数的参数传递)? parse_ini_file?

标签: php class global-variables


【解决方案1】:

当在函数中包含 (include/require) 文件时,该文件中的所有变量声明都会获得函数的范围。所以$testVar是在callingClass::__construct的范围内创建的。 由于您使用require_once它不会在calledClass::__construct 内的其他地方重新创建!它仅在调用 calledClass 时有效,因为您实际上是第一次在其中包含该文件。

它与 OOP 完全无关,只是 rules of function scope 和您对 require_once 的特殊使用。

【讨论】:

  • 感谢您对include/require 的解释。但我需要更多帮助。当我在示例中将 print_r(get_included_files()); 添加到 calledClass 时,它显示 'Array ( [0] => D:\htdocs\test\callingClass.php [1] => D:\htdocs\test\config.php [2] => D:\htdocs\test\ calledClass.php ) '。这意味着 config.php 包含在 calledClass 中。什么会干扰从 calledClass::__construct 中包含的文件中读取变量?
猜你喜欢
  • 2021-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-27
  • 2014-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多