Using `$this` in an anonymous function in PHP pre 5.4.0

前端 未结 5 601

The PHP manual states

It is not possible to use $this from anonymous function before PHP 5.4.0

on the anonymous

5条回答
  •  温柔的废话
    2020-12-02 22:33

    Don't always rely on PHP to pass objects by reference, when you are assigning a reference itself, the behavior is not the same as in most OO languages where the original pointer is modified.

    your example:

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

    should be:

    $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

提交回复
热议问题