program story

PHP 5.4.0 이전의 익명 함수에서`$ this` 사용

inputbox 2020. 9. 17. 07:51
반응형

PHP 5.4.0 이전의 익명 함수에서`$ this` 사용


PHP 매뉴얼 상태

$thisPHP 5.4.0 이전에는 익명 함수에서 사용할 수 없습니다.

상의 익명 함수 페이지 . 그러나 $this변수 에 할당 use하고 함수 정의 명령문에 변수를 전달하여 작동시킬 수 있음을 발견했습니다 .

$CI = $this;
$callback = function () use ($CI) {
    $CI->public_method();
};

이것이 좋은 습관입니까? PHP 5.3을 사용하여 익명 함수 내부
에 액세스하는 더 좋은 방법이 $this있습니까?


보호 된 메서드 나 개인 메서드를 호출하려고하면 실패합니다. 그렇게 사용하는 것은 외부에서 호출하는 것으로 간주되기 때문입니다. 내가 아는 한 5.3에서이 문제를 해결할 수있는 방법은 없지만 PHP 5.4가 나오면 예상대로 작동합니다.

class Hello {

    private $message = "Hello world\n";

    public function createClosure() {
        return function() {
            echo $this->message;
        };
    }

}
$hello = new Hello();
$helloPrinter = $hello->createClosure();
$helloPrinter(); // outputs "Hello world"

더 나아가 익명 함수 (클로저 리 바인딩)에 대해 런타임시 $ this가 가리키는 것을 변경할 수 있습니다.

class Hello {

    private $message = "Hello world\n";

    public function createClosure() {
        return function() {
            echo $this->message;
        };
    }

}

class Bye {

    private $message = "Bye world\n";

}

$hello = new Hello();
$helloPrinter = $hello->createClosure();

$bye = new Bye();
$byePrinter = $helloPrinter->bindTo($bye, $bye);
$byePrinter(); // outputs "Bye world"

사실상 익명 함수는 bindTo () 메서드를 갖게 되는데, 첫 번째 매개 변수는 $ this가 가리키는 것을 지정하는 데 사용될 수 있고 두 번째 매개 변수는 가시성 수준이 무엇이어야하는지 제어 합니다 . 두 번째 매개 변수를 생략하면 가시성은 "외부"에서 호출하는 것과 같습니다. 공용 속성에만 액세스 할 수 있습니다. 또한 bindTo가 작동하는 방식을 기록하십시오. 원래 함수를 수정하지 않고 함수를 반환합니다 .


참조로 객체를 전달하기 위해 항상 PHP에 의존하지 마십시오. 참조 자체를 할당 할 때 동작은 원래 포인터가 수정 된 대부분의 OO 언어와 동일하지 않습니다.

당신의 예 :

$CI = $this;
$callback = function () use ($CI) {
$CI->public_method();
};

해야한다:

$CI = $this;
$callback = function () use (&$CI) {
$CI->public_method();
};

NOTE THE REFERENCE "&" and $CI should be assigned after final calls on it has been done, again else you might have unpredictable output, in PHP accessing a reference is not always the same as accessing the original class - if that makes sense.

http://php.net/manual/en/language.references.pass.php


That is the normal way it was done.
b.t.w, try to remove the & it should work without this, as objects pass by ref any way.


That seems alright if your passing by reference it's the correct way to do it. If your using PHP 5 you don't need the & symbol before $this as it will always pass by reference regardless.


This is fine. I should think you could do this also:

$CI = $this;

... since assignations involving objects will always copy references, not whole objects.

참고URL : https://stackoverflow.com/questions/8391099/using-this-in-an-anonymous-function-in-php-pre-5-4-0

반응형