【问题标题】:Call to member function on a non-object调用非对象的成员函数
【发布时间】:2012-01-02 04:51:09
【问题描述】:

我已经阅读了几个已经存在与此名称或类似名称的主题。似乎没有一个能完全解决我的情况。

我的 utils.php 班级收到此错误。

Notice: Undefined variable: debug in /app/www/utils.php on line 89 Fatal error: Call to a member function debug() on a non-object in /app/www/utils.php on line 89

我这样定义变量debug

require_once('PHPDebug.php');
$debug = new PHPDebug();

然后像这样调用它(在第 89 行):

$debug->debug($message);

我如此困惑的原因是我从index.php 复制并粘贴了这些行,并且调用工作正常。

如果需要,我可以包含指向 index.phputils.php 文件以及 PHPDebug.php 的链接。

【问题讨论】:

  • 首先在第 89 行之前执行 var_dump($debug);并发布你得到的。
  • 我把它放在前面的行上,所以新的第 89 行,得到:Notice: Undefined variable: debug in /app/www/utils.php on line 89 NULL
  • $debug之前的声明是不是像89一样?
  • 好吧,你明白了。出于我们无法知道的原因,因为您没有发布整个代码,$debug var 不再是 PHPDebug 的实例,而是为空。因此,您不能在 null var 上调用方法。
  • 可能是因为我在文件中的任何函数(不是类)之外定义了 $debug,然后我在函数中访问了 $debug(在第 89 行等)?

标签: php scope variable-assignment require-once


【解决方案1】:

感谢您的最后评论,您的问题的解决方案是在函数中将$debug 声明为global。因此,你应该有这样的东西:

require_once('PHPDebug.php');
$debug = new PHPDebug();

function myfunction()
{
   global $debug;

   // some code

   $debug->debug($message);
}

您可以在official doc 中阅读有关全球的更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-18
    相关资源
    最近更新 更多