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

3

I have following setup.

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 时,出现以下错误信息:在 settings.php 的第3行创建默认对象时出现严格标准警告
如果我将 $obj->dostuff = true; 放在 config.php 中,则不会产生错误消息。
有人能解释一下为什么会出现这个错误吗?我不是要求如何修复它,只是想了解为什么会出现这个错误。 编辑: 我犯了一个错误,我有两个 config.php 类用于网站的每个部分,并且我只更改了其中一个的内容,导致另一个包含顺序仍然是旧的,现在在正确的顺序加载后,它可以正常工作。

obj->dostuff 的内容是什么? - Explosion Pills
在settings.php文件的第三行是什么? - Ibu
我的错,不是function(),而是在settings.php文件的第3行中的$this:$obj->dostuff = true; - John Smith
MyClass 中有什么吗? - Samuel Cook
在config.php文件中,你是直接将$obj->dostuff放在require_once之前吗? - dev-null-dweller
1
我需要将 $obj->dostuff = true; 放到 settings.php 中,这是目标。无论我在 config.php 的哪个位置放置它,都没有看到严格标准错误。 - John Smith
2个回答

2

看起来是作用域问题。在settings.php文件中,$obj不可访问。PHP正在从标准类创建新的对象,并给出警告。您可以通过添加以下代码进行确认:

echo get_class($obj);

在您的settings.php文件中,仅在产生错误的那一行后面。如果它输出"StdClass",那么就是这种情况。
您确定$obj不是在函数/方法内创建的吗?

$obj是在脚本加载时运行的一行代码创建的,就像我之前所说的那样。 - John Smith

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;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接