Search code examples
phpscopevariable-assignmentrequire-once

Call to member function on a non-object


I've read several of the threads that already exist with this, or a similar, name. None seems to address my situation exactly.

I'm getting this error from my utils.php class.

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

I define the variable debug like this:

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

and then call it (in line 89) like this:

$debug->debug($message);

The reason I'm so baffled is that I copied and pasted these lines from my index.php and that call works just fine.

If you want, I can include links to the index.php and utils.php files, as well as PHPDebug.php.


Solution

  • Thanks to your last comment, the solution to your problem is to declare $debug as global within the function. Thus, you should have something like this:

    require_once('PHPDebug.php');
    $debug = new PHPDebug();
    
    function myfunction()
    {
       global $debug;
    
       // some code
    
       $debug->debug($message);
    }
    

    You can read more about global in the official doc.