Storing a Closure Function in a Class Property in PHP

后端 未结 6 1023
清歌不尽
清歌不尽 2021-01-21 07:37

ok I do have the code below

bar();
       }
    }

    $mee         


        
6条回答
  •  -上瘾入骨i
    2021-01-21 08:16

    You will not be able to do that.

    Take for example this code:

    class T {
      function foo() {
        echo 'T::foo';
      }
    }
    
    $t = new T;
    $t->foo = function() {
      echo 'Closure::foo';
    };
    $t->foo();
    

    It works fine on PHP 5.4.6 and/or PHP 5.3.16, however it will result in T::foo getting printed.

    This happens because methods, in PHP, are not modifiable class properties, as they are for example in javascript.

    However,

    $foo = $t->foo;
    $foo();
    

    will print Closure::foo as expected.

提交回复
热议问题