tags:

views:

46

answers:

3

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?

A: 

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

Lotus Notes
The problem here is that there seem to be situations in which you can call a class method without loading the class's scope. It's not a problem with inheritance that can be resolved by late static binding.
Brooks
+1  A: 

You're not passing any parameters, but your method is looking for them. Try

call_user_func("MyClass::search", $args);

This works in php 5.3.1, but call_user_func("MyClass::search"); doesn't

Andrew Sledge
This is correct, I just tried it in PHP 5.3.x and it works fine you just need the args, with <5.2.x it'll give you that error. Code I used class MyClass{ public static function search($args){ $results = "some query"; $ordered_results = self::stack($results); return $ordered_results; } public static function stack($args){ //Sort the results return 'query some'; }}$args = array('search_term'=>"Jimmy Hoffa");print call_user_func("MyClass::search", $args);
Viper_Sb
You missed the point of the question entirely. Read the question not the code. I'm not trying to get something to work, I'm trying to identify a set of limitations.
Brooks
A: 

Try this:

call_user_func(array('MyClass', 'search'));

See also example #4 on http://php.net/call_user_func

divideandconquer.se
You can pass static object methods as the first param
Andrew Sledge
But doesn't that require PHP 5.3.0?
divideandconquer.se
we went over that in the initial discussion already.
Brooks