[英]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 ? 是否可以在类方法中创建函数,如何调用它?
ie 即
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:
从PHP 5.3开始,您可以使用匿名函数 :
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;
}
}
}
它可以完成,但由于函数是在全局范围内定义的,如果方法被调用两次将导致错误,因为PHP引擎将考虑在第二次调用期间重新定义函数。
Use "function_exists" to avoid errors. 使用“function_exists”来避免错误。
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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.