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
You can also use self::CONST instead of $this->CONST if you want to call a static variable or function of the current 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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With