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

is it possible to create function inside a class method and how do I call it ?

i.e.

class Foo
{
    function bar($attr)
    {
       if($attr == 1)
       {
          return "call function do_something_with_attr($attr)";
       }
       else
       {
          return $attr;
       }

       function do_something_with_attr($atr)
       {
          do something
          ...
          ...
          return $output;
       }
    }
}

thank you in advance

It can be done, but since functions are defined in the global scope this will result in an error if the method is called twice since the PHP engine will consider the function to be redefined during the second call.

Use "function_exists" to avoid errors.

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


    }
}

Yes. As of PHP 5.3, You can use anonymous functions for 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;
        }
     }
}