Accessing global variable within static class method

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mikejw
Forum Newbie
Posts: 2
Joined: Sat Nov 21, 2009 7:16 am

Accessing global variable within static class method

Post 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!
User avatar
BlaineSch
Forum Commoner
Posts: 28
Joined: Sun Jun 07, 2009 4:28 pm
Location: Trapped in my own little world.

Re: Accessing global variable within static class method

Post by BlaineSch »

What error are you getting?
mikejw
Forum Newbie
Posts: 2
Joined: Sat Nov 21, 2009 7:16 am

Re: Accessing global variable within static class method

Post by mikejw »

"Call to a member function printException() on a non-object in /var/www/sites/test/index.php on line 21."
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Accessing global variable within static class method

Post by Jonah Bron »

You're class is calling itself. I think you want to skip the global, and just use $this.
User avatar
iankent
Forum Contributor
Posts: 333
Joined: Mon Nov 16, 2009 4:23 pm
Location: Wales, United Kingdom

Re: Accessing global variable within static class method

Post 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
Post Reply