开发者

php: can I create and call function inside a class method?

开发者 https://www.devze.com 2023-02-05 12:38 出处:网络
is it possible开发者_运维问答 to create function inside a class method and how do I call it ? i.e.

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


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


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


    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消