Owh — my — gawd!
I’ve just noticed a very pretty patch by Sara Golemon (I think?) that allows static __call magic function.
If that sounds weird or plain useless then… you are just about right…
The new magic function is currently (php5.3 and php6 CVS HEAD) called __callStatic and you should be aware that it has some issues.
So, what good is this…
It would be a good way to create overloadable static methods that would allow the user to call the same class method with different number of arguments or different argument types and get different results.
Same way overloading works in other programming languages.
very simple example.
users::get(1); //Returns user with id 1
users::get(“email”, “b.gates@microsoft.com”); //Returns user with email address b.gates@…
There should be other cute things that could be done with this, especially if it was backported earlier in php5.x where namespaces didn’t exist.
But since the first version to implement this will probably be 5.3 that will also include namespaces the glory of the static __call method is faded.
To be honest I wasn’t looking for this when I bumped onto it.
I was looking for a way to implement a static __get method.
Since the lovely core developers of php actively deny to let the users define their own custom superglobals (like $_SESSION, $_POST, etc) I’ve been trying to find a way to call some objects from any scope without having to register them as global first or call them through a registry or singleton pattern.
I frequently end up having several global objects that everything in my Php application needs and having to remember to global everything is a pain in my ass.
A registry or a singleton pattern would seem the way to go here but still I don’t quite like either.
object::getInstance()->doSomething(); //Singleton pattern inside the class
singleton::getInstance(“object”)->doSomething(); //Generic registry pattern
Now imagine that you could define $object as a superglobal…
$object::doSomething();
The problem with this is that in order to do this you need to have the runkit extension or custom patch your php but then you have to watch your code portability go down the drain.
So my last hope was using a static __get method that would return the global object using the requested variable. (did this make any sense?)
< ?php
class superglobals
{
public static function __get($var)
{
global ${$var};
return ${$var};
}
}
?>
This is currently wrong for so, sooo many reasons, but wouldn’t it be pretty if it actually worked?
There are no static __get or __set methods not even in the php6 schedule and this saddens me but I’ve got faith in the core php team that they’ll make up for it with namespaces, threadding and native utf support. — And maybe custom superglobals? Pretty please?
JamesD 11:48 on June 11, 2009 Permalink |
Thanks for the useful info. It’s so interesting