php:我可以在类方法中创建和调用函数吗?

php:我可以在类方法中创建和调用函数吗?,php,class,function,Php,Class,Function,可以在类方法内部创建函数吗?我如何调用它 i、 e 福班 { 功能栏($attr) { 如果($attr==1) { 返回“调用函数do_something_with_attr($attr)”; } 其他的 { 返回$attr; } 函数do\u something\u with\u attr($atr) { 做点什么 ... ... 返回$output; } } } 预先感谢 < P>可以完成,但是由于函数在全局范围内被定义,如果PHP引擎将考虑在第二次调用期间重新定义函数,则该方法会导致错误

可以在类方法内部创建函数吗?我如何调用它

i、 e

福班 { 功能栏($attr) { 如果($attr==1) { 返回“调用函数do_something_with_attr($attr)”; } 其他的 { 返回$attr; } 函数do\u something\u with\u attr($atr) { 做点什么 ... ... 返回$output; } } }

预先感谢

< P>可以完成,但是由于函数在全局范围内被定义,如果PHP引擎将考虑在第二次调用期间重新定义函数,则该方法会导致错误。

< P>使用“函数存在”来避免错误。

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;
       }


    }
}

对。从PHP 5.3开始,您可以使用:

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;
        }
     }
}

使用普通的(可能是静态的)类方法不能实现同样的功能吗?正如Ignacio所写,我得到了一个错误。Zerkms,请您详细解释一下如何使用函数_exists()求解谢谢。php文档是一件很棒的事情@m1k3y02:您不应该在方法中声明全局函数。声明其他具有
保护
私有
可见性的方法,并使用
$this
调用它们。除非你真的需要一个全局函数。。。
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;
        }
     }
}