Any way to use __call statically?

windows

Guest
I want to use the __call overloader in a static context, but the PHP 5 docs say that __call must not be called statically. Is there anyway to get around this? Basically, I want to be able to call php functions through my class like:

FooClass::strtoupper('a string');

I'm doing this because I'm creating a filtering class, and I want to be able to use the class whether it's a built-in function or one in the class for consistency.

Any ideas?You are pulling some intense magic there...

I am going to offer an alternative because I think you will be limited here...


class Foo
{
function __call($name, $argv)
{
static $list = '';

if ($list === '') { $list = get_defined_functions(); }

if (in_array($name, $list))
{
// Call the method(s)
}
else
{
// Trigger an error?
}
}
}Maybe a Singleton approach might work.

class Foo
{
private static $instance;
public static function instance()
{
if( !self::$instance instanceof self )
{
self::$instance = new Foo();
}
return self::$instance;
}
public function __call( $method, $args )
{
// Implementation
}
}
Foo::instance()->strtoupper( 'foo' );

Edit: I'm not sure what benefit routing every built-in function through your class will do, it will slow down all PHP functions, and as for consistency, well do I really need to go check if you have provided an alternate function in your class for every PHP function?I do something similar to what Shrike suggested, except I don't make it a singleton. I certainly don't wrap every PHP function though, and usually do not just wrap a single function unless I know it something that is going to be trumped later on (such as mb_string when PHP 6 arrives) or usually want defaults that differ from the PHP defaults. Normally though, I just create them for utility functions that PHP doesn't offer a built in function for, or for a common series of function calls that occur throughout the application, such as saving a file where you generally want to save it and chmod it to an appropriate value.

My approach looks like this:
class Foo {

public static function utils($name, $input = null) {
$class = $name . 'Util';
$util = new $class($input);
return $util;
}

}



class StringUtil {

protected $string;

public function __construct($string = null) {
$this->string = $string;
}

public function toUpper() {
return mb_strtoupper($this->string, 'UTF-8');
}

}


Foo::utils('String', 'bar b閸厇le')->toUpper();

I like it because it is easy to expand upon. Though it is coded so the utility constructor only can get a single parameter, this could be changed, but I haven't yet found a need to do so. So far it has made more sense to pass extra parameters into the method when needed.
 
Back
Top