【问题标题】:Assign a function to a class variable in PHP [duplicate]将函数分配给PHP中的类变量[重复]
【发布时间】:2019-07-21 02:33:39
【问题描述】:

我可以将函数分配给 PHP 中的类变量,即$this->variable

但是,当我尝试执行该函数时,它失败了:

FATAL ERROR Call to undefined method a::f()

这里有一个sn-p来说明问题:

<?php

new a();

class a
{
    private $f;
    function __construct()
    {
        $g = function() { echo "hello g"; };
        $g(); //works

        $this->f = function() { echo "hello f"; };
        $this->f();  //FATAL ERROR Call to undefined method a::f()
    }
}

【问题讨论】:

    标签: php php-7 anonymous-function php-5.6 php-5.4


    【解决方案1】:

    看起来语法让 PHP 感到困惑。

    将函数分配回一个局部变量,一切都很好!

    <?php
    
    new a();
    
    class a
    {
        private $f;
        function __construct()
        {
            $g = function() { echo "hello g"; };
            $g();
    
            $this->f = function() { echo "hello f"; };
            $f = $this->f;   //ASSIGN TO LOCAL VARIABLE!!!
            $f();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-29
      • 1970-01-01
      • 1970-01-01
      • 2013-01-03
      • 2018-07-10
      • 2015-11-19
      • 2022-07-21
      • 2011-07-28
      相关资源
      最近更新 更多