Defining class methods in PHP

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

    As PHP 5.3 supports closures, you can dynamically define instance methods as variables holding closures:

    $class->foo = function (&$self, $n) {
      print "Current \$var: " . $self->var . "\n";
      $self->var += $n;
      print "New \$var:     " .$self->var . "\n";
    };
    

    Taking $self (you can't use $this outside object context) as a reference (&), you can modify the instance.

    However, problems occur when you try to call the function normally:

    $class->foo(2);
    

    You get a fatal error. PHP thinks foo is a method of $class, because of the syntax. Also, you must pass the instance as the first argument.

    There is luckily a special function for calling functions by name called call_user_func:

    call_user_func($class->foo, &$class, 2);
    # => Current $var: 0
    # => New $var:     2
    

    Just remember to put & before the instance variable.

    What's even easier is if you use the __call magic method:

    class MyClass {
      public function __call ($method, $arguments)  {
        if (isset($this->$method)) {
          call_user_func_array($this->$method, array_merge(array(&$this), $arguments));
        }
      }
    }
    

    Now you can call $class->foo(2) instead. The magic __call method catches the call to an unknown method, and calls the closure in the $class->foo variable with the same name as the called method.

    Of course, if $class->var was private, the closure in stored in the $class->foo variable wouldn't be able to access it.

提交回复
热议问题