Page 1 of 1

Accessing global variable within static class method

Posted: Sat Nov 21, 2009 7:19 am
by mikejw
I'm trying to do the following but I'm getting a fatal error. Can anyone help?

Code: Select all

 
<?php
 
class Boot
{
  public function __construct()
  {
    set_exception_handler('Boot::exception');
    $this->doSomeStuff();
  }
 
  public function doSomeStuff()
  {
    throw new Exception('throwing some exception.');
  }
 
  public static function exception($e)
  {
    global $boot;
    //    $boot = $GLOBALS['boot'];                                                                                              
    $boot->printException($e);
  }
 
  public function printException($e)
  {
    echo $e->getMessage();
  }
}
 
$boot = new Boot();
?>
 
Cheers!

Re: Accessing global variable within static class method

Posted: Sat Nov 21, 2009 8:21 am
by BlaineSch
What error are you getting?

Re: Accessing global variable within static class method

Posted: Sat Nov 21, 2009 8:22 am
by mikejw
"Call to a member function printException() on a non-object in /var/www/sites/test/index.php on line 21."

Re: Accessing global variable within static class method

Posted: Sat Nov 21, 2009 6:37 pm
by Jonah Bron
You're class is calling itself. I think you want to skip the global, and just use $this.

Re: Accessing global variable within static class method

Posted: Sat Nov 21, 2009 7:14 pm
by iankent
Two things I think. First, your object constructor is calling doSomeStuff() which is throwing an exception, so the object is not being created (you should be able to verify this with var_dump). Try moving the exception out of the constructor and into a method thats called on the object after its been created.

Second, and probably the reason for your problem, the method printException is not a static method so it's not accessible by Boot::exception(). Easiest solution is to add the static keyword to that function.

hth