nickf
nickf

Reputation: 546273

Using __call with static classes?

Is it possible to use the __call magic method when calling functions statically?

Upvotes: 9

Views: 8217

Answers (3)

David
David

Reputation: 18281

Not yet, there is a proposed (now available) __callStaticDocs method in the pipeline last I knew. Otherwise __call and the other __ magic methods are not available for use by anything but the instance of a object.

Upvotes: 16

nickf
nickf

Reputation: 546273

You have to use the other magic method, __callStatic - this is only available in PHP >= 5.3, which hasn't actually been released yet.

Upvotes: 9

Tom Schaefer
Tom Schaefer

Reputation: 897

As described before, there is no magic static caller. But you can code like this:

   class First {
        public static function test1(){
            return 1;
        }
        public static function test2(){
            return 2;
        }
    }


    class Second {
        public static function test1(){
            if(func_num_args()>0){
                return func_get_args();
            }
            return 21;
        }
        public static function test2(){
            return 22;
        }
    }

    class StaticFactory {
        public static function factory($class, $method){
            if(func_num_args()>2){
                $args = func_get_args();
                array_shift($args);
                array_shift($args);
                return call_user_func_array(array($class,$method), $args);
            }else{
            return call_user_func_array(array($class,$method), array());
            }
        }
    }

    print_r(StaticFactory::factory("Second", "test1", 1, false, true));

    print_r(StaticFactory::factory("First", "test1"));

Upvotes: 0

Related Questions