Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 837
m1k3y3 Avatar asked Jan 16 '11 23:01

m1k3y3


People also ask

How do you call a function within a class in PHP?

You can also use self::CONST instead of $this->CONST if you want to call a static variable or function of the current class.

Can you call a function within a class?

To call a function within class with Python, we call the function with self before it. We call the distToPoint instance method within the Coordinates class by calling self. distToPoint . self is variable storing the current Coordinates class instance.

How do I call a function in the same class?

In this program, you have to first make a class name 'CallingMethodsInSameClass' inside which you call the main() method. This main() method is further calling the Method1() and Method2(). Now you can call this as a method definition which is performing a call to another lists of method.

Can we call a function inside a function in PHP?

Note that PHP doesn't really support "nested functions", as in defined only in the scope of the parent function. All functions are defined globally. See the docs. Thanks, so inner function does not get called.


2 Answers

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;
        }
     }
}
like image 186
Russell Hankins Avatar answered Sep 20 '22 14:09

Russell Hankins


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.

like image 35
Ignacio Vazquez-Abrams Avatar answered Sep 20 '22 14:09

Ignacio Vazquez-Abrams