Programing

PHP : 클래스 함수를 콜백으로 사용하는 방법

crosscheck 2020. 10. 17. 09:12
반응형

PHP : 클래스 함수를 콜백으로 사용하는 방법


이 질문에 이미 답변이 있습니다.

콜백으로 사용하려는 메서드가있는 클래스가 있습니다. 인수로 전달하는 방법?

Class MyClass {

    public function myMethod() {
        $this->processSomething(this->myCallback); // How it must be called ?
        $this->processSomething(self::myStaticCallback); // How it must be called ?
    }

    private function processSomething(callable $callback) {
        // process something...
        $callback();
    }

    private function myCallback() {
        // do something...
    }

    private static function myStaticCallback() {
        // do something...
    }   

}

UPD : 동일한 방법을 사용하지만 static방법에서 ( $this사용할 수없는 경우)


검사 callable매뉴얼은 콜백으로 함수를 전달하는 모든 다른 방법을 볼 수 있습니다. 여기에 해당 설명서를 복사하고 시나리오에 따라 각 접근 방식의 몇 가지 예를 추가했습니다.

호출 가능


  • PHP 함수는 그 이름을 문자열로 전달한다. array () , echo , empty () , eval () , exit () , isset () , list () , print 또는 unset () 과 같은 언어 구조를 제외한 모든 내장 또는 사용자 정의 함수를 사용할 수 있습니다. .
  // Not applicable in your scenario
  $this->processSomething('some_global_php_function');

  • 인스턴스화 된 객체메서드는 인덱스 0 의 객체 와 인덱스 1 의 메서드 이름을 포함하는 배열로 전달됩니다 .
  // Only from inside the same class
  $this->processSomething([$this, 'myCallback']);
  $this->processSomething([$this, 'myStaticCallback']);
  // From either inside or outside the same class
  $myObject->processSomething([new MyClass(), 'myCallback']);
  $myObject->processSomething([new MyClass(), 'myStaticCallback']);

  • 인덱스 0 의 객체 대신 클래스 이름을 전달하여 해당 클래스의 객체를 인스턴스화하지 않고 정적 클래스 메서드 를 전달할 수도 있습니다 .
  // Only from inside the same class
  $this->processSomething([__CLASS__, 'myStaticCallback']);
  // From either inside or outside the same class
  $myObject->processSomething(['\Namespace\MyClass', 'myStaticCallback']);
  $myObject->processSomething(['\Namespace\MyClass::myStaticCallback']); // PHP 5.2.3+
  $myObject->processSomething([MyClass::class, 'myStaticCallback']); // PHP 5.5.0+

  • Apart from common user-defined function, anonymous functions can also be passed to a callback parameter.
  // Not applicable in your scenario unless you modify the structure
  $this->processSomething(function() {
      // process something directly here...
  });


Since 5.3 there is a more elegant way you can write it, I'm still trying to find out if it can be reduced more

$this->processSomething(function() {
    $this->myCallback();
});

You can also to use call_user_func() to specify a callback:

public function myMethod() {

    call_user_func(array($this, 'myCallback'));
}

private function myCallback() {
    // do something...
}

참고URL : https://stackoverflow.com/questions/28954168/php-how-to-use-a-class-function-as-a-callback

반응형