PHP严格标准:从空值创建默认对象

时间:2012-11-01 20:55:16

标签: php include

我有以下设置。

index.php

   require_once "common.php";
   ...

的common.php

   ...
   $obj = new MyClass;
   require_once "config.php"
   ...

的config.php

   ...
   require_once "settings.php";
   ...

的settings.php

   $obj->dostuff = true;
   ...

当我打开 index.php 时,我得到:严格标准:在3中的settings.php中从空值创建默认对象

如果我将$obj->dostuff = true;放在 config.php 中,则不会产生错误消息。

有人可以解释为什么我会收到这个错误吗?我不是问如何解决它只是理解为什么。

编辑:我的错误我为网站的每个部分都有2个config.php类,我只改变了其中一个的东西,在另一个中留下旧的包含订单现在它在所有加载后工作正常正确的订单。

2 个答案:

答案 0 :(得分:2)

这看起来是一个范围问题。在settings.php中,无法访问$ obj。 PHP正在从标准类创建一个新的,并给你一个警告。您可以通过

确认
echo get_class($obj);
你的settings.php中的

,就在产生错误的行之后。如果它回声“StdClass”,那就是这种情况。

你确定$ obj不是在函数/方法中创建的吗?

答案 1 :(得分:0)

如果$ obj是系统范围的全局可访问对象,您可以使用单例模式从任何地方访问:

class MyClass
{
    protected static $_instance;

    static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
}

然后,您可以在此课程中创建方法。要获取对象本身,只需调用:

$obj = MyClass::getInstance();

此外,如果您只想调用其中一种方法,但不需要返回任何内容:

MyClass::getInstance()->objectMethod();

我发现这是组织基于单一系统的整体操作的一种非常有效的方法。

实际上,我的项目使用它来从系统中的任何位置进行配置:

class syConfig
{
    protected static $_instance;

    private $_config;

    static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function load($xmlString)
    {
        $xml = simplexml_load_string($xmlString);
        $this->_config = $xml;
    }

    public function getConfig()
    {
        return $this->_config;
    }
}