【问题标题】:php: can I create and call function inside a class method?php:我可以在类方法中创建和调用函数吗?
【发布时间】:2011-06-10 04:26:21
【问题描述】:

是否可以在类方法中创建函数以及如何调用它?

Foo 类 { 功能栏($attr) { 如果($attr == 1) { return "调用函数 do_something_with_attr($attr)"; } 别的 { 返回 $attr; } 函数 do_something_with_attr($atr) { 做一点事 ... ... 返回$输出; } } }

提前谢谢你

【问题讨论】:

  • 使用普通的(可能是静态的)类方法不能完成同样的事情吗?

标签: php class function


【解决方案1】:

是的。自 PHP 5.3 起,您可以为此使用 anonymous functions

class Foo
{
    function bar($attr)
    {
        $do_something_with_attr = function($atr)
        {
            //do something
            //...
            //...
            $output = $atr * 2;
            return $output;
        };

        if ($attr == 1)
        {
            return $do_something_with_attr($attr);
        }
        else
        {
            return $attr;
        }
     }
}

【讨论】:

    【解决方案2】:

    可以这样做,但是由于函数是在全局范围内定义的,如果该方法被调用两次,则会导致错误,因为 PHP 引擎会在第二次调用期间考虑重新定义该函数。

    【讨论】:

    • 我收到了 Ignacio 写的错误。 Zerkms,您能否更详细地解释如何使用 function_exists() 解决? - 谢谢。
    • @m1k3y02:您不必在方法中声明全局函数。使用protectedprivate 可见性声明其他方法,并使用$this 调用它们。除非你真的需要一个全局函数……
    【解决方案3】:

    使用“function_exists”来避免错误。

    class Foo
    {
        function bar($attr)
        {
    
           if (!function_exists("do_something_with_attr")){ 
               function do_something_with_attr($atr)
               {
                  do something
                  ...
                  ...
                  return $output;
               }
           }
    
           if($attr == 1)
           {
              return do_something_with_attr($attr);
           }
           else
           {
              return $attr;
           }
    
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-15
      • 2017-11-13
      • 2017-03-09
      • 2022-09-27
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多