16

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

1
  • Could the same not be accomplished using a normal (perhaps static) class method? Commented Jan 16, 2011 at 23:59

3 Answers 3

13

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;
        }
     }
}
Sign up to request clarification or add additional context in comments.

Comments

10

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.

3 Comments

I am getting error as Ignacio wrote. Zerkms, could you please explain in more details how to solve with function_exists() ? - Thank You.
The php documentation is a wonderful thing php.net/manual/en/function.function-exists.php
@m1k3y02: You shouldn't have to declare global functions within methods. Declare other methods with protected or private visibility instead, and call them using $this. Unless you really really need a global function...
3

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


    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.