Defining class methods in PHP

后端 未结 8 1354
臣服心动
臣服心动 2021-01-05 10:55

Is it possible in PHP (as it is in C++) to declare a class method OUTSIDE the class definition?

8条回答
  •  我在风中等你
    2021-01-05 11:00

    You could perhaps override __call or __callStatic to locate a missing method at runtime, but you'd have to make up your own system for locating and calling the code. For example, you could load a "Delegate" class to handle the method call.

    Here's an example - if you tried to call $foo->bar(), the class would attempt to create a FooDelegate_bar class, and call bar() on it with the same arguments. If you've got class auto-loading set up, the delegate can live in a separate file until required...

    class Foo {
    
        public function __call($method, $args) {
            $delegate="FooDelegate_".$method;
            if (class_exists($delegate))
            {
                 $handler=new $delegate($this);
                 return call_user_func_array(array(&$handler, $method), $args);
            }
    
    
        }
    
    }
    

提交回复
热议问题