Search code examples
phpoopclassself

PHP5 Class scope quirks


Hey php gurus. I'm running into some bizarre class scope problems that clearly have to do with some quirk in php. Can anyone tell me what out-of-the-ordinary situations might give the following error...

Fatal error: Cannot access self:: when no class scope is active in MyClass.php on line 5

Now, obviously if I were to use self:: outside of the class, I'd get errors... but I'm not. Here is a simplified version of the situation...

//file1
class MyClass{
   public static function search($args=array()){
       $results = MyDbObject::getQueryResults("some query");
       $ordered_results = self::stack($results); //Error occurs here

       return $ordered_results;
   }
   public static function stack($args){
       //Sort the results
       return $ordered_results;
   }
}

//file 2
include_once("MyClass.php");
$args = array('search_term'=>"Jimmy Hoffa");
$results = MyClass::search($args);

given this setup how can I get the error above? Here is what I've found so far...

MyClass::search($args) //does not give the error (usually)
call_user_func("MyClass::search"); // this gives the error!

Any other situations?


Solution

  • If I understand correctly, you are looking for Late Static Binding. This feature requires PHP version 5.3 at least.