Defining class methods in PHP

后端 未结 8 1363
臣服心动
臣服心动 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:11

    No, as of PHP 5.2. However, you may use __call magic method to forward call to arbitrary function or method.

    class A {
    
        public function __call($method, $args) {
            if ($method == 'foo') {
                return call_user_func_array('bar', $args);
            }
        }
    
    }
    
    function bar($x) {
        echo $x;
    }
    
    $a = new A();
    $a->foo('12345'); // will result in calling bar('12345')
    

    In PHP 5.4 there is support for traits. Trait is an implementation of method(s) that cannot be instantiated as standalone object. Instead, trait can be used to extend class with contained implementation. Learn more on Traits here.

提交回复
热议问题