【问题标题】:PHP and some global variablesPHP 和一些全局变量
【发布时间】:2010-11-23 08:05:40
【问题描述】:
require_once'modules/logger.php';                                                         
$Logger = new Logger();

require_once 'templates/list.php';
$Templates = new templatesList();

require_once 'widgets/list.php';
$Widgets = new widgetsList();

我在templates/list.phpwidgets/list.php 中使用$Logger$Templates我在/widgets/list.php中使用。

上面的代码抛出这个错误:

注意:未定义变量:Logger in .../templates/list.php 第 99 行 致命错误:调用成员函数 toLog() 中的非对象 .../templates/list.php 第 99 行

UPD 这是第 99 行:

$Logger->toLog( $contentData );

【问题讨论】:

  • 你的第 99 行在哪里?可以发一下吗?

标签: php require-once


【解决方案1】:

您确定您没有在 /templates/list.php 的开头某处取消设置 $Logger 吗?

在初始化之后和使用之前尝试 var_dumping() $Logger。

【讨论】:

    【解决方案2】:

    如果您想在对象方法中使用$Logger,您需要在该方法中将其标记为全局。如果不这样做,您最终将创建一个新的本地 $Logger 变量。我怀疑这就是问题所在。例如:

    class templatesList {
        public function __construct() {
            global $Logger;
            //now we can use $logger.
        }
    }
    

    但是,将 $Logger 传递给每个需要使用它的对象的构造函数可能会更好。全局变量通常不被认为是好的做法。

    class templatesList {
        protected $Logger;
        public function __construct(Logger $Logger) {
            //now we can use $logger.
    
            //store reference we can use later
            $this->Logger = $Logger;
        }
    
        public function doSomething() {
            $this->Logger->log('something');
        }
    }
    
    new templatesList($Logger);
    

    【讨论】:

    • 我尝试使用 global 关键字,但对我没有帮助。也许将它传递给构造函数会更好......好的,谢谢。
    • 对于 Logger 和 Templateslist 类(听起来两者都只需要一个实例),我建议使用单例模型。无需传递变量或使用全局变量。
    • 虽然单例版本的 Logger 可能是合适的,但单例只是伪装的全局变量
    猜你喜欢
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 2019-11-30
    相关资源
    最近更新 更多