简体   繁体   English

php:我可以在类方法中创建和调用函数吗?

[英]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.

相关问题 如何在php中自己的类中调用函数或方法? - How to call a function or method inside its own class in php? 如何在php类中调用函数? - How can I call a function in a php class? 我可以动态创建一个类名,然后用它在PHP中调用该类的静态函数吗? - Can I dynamically create a class name and then use it to call static function of that class in PHP? PHP调用Class方法/函数 - PHP call Class method / function 为什么在没有将方法声明为static关键字的情况下静态地在类中调用PHP函数? - Why can I call a PHP function in a class statically without the method having been declared the static keyword? 如何在不使用全局变量的情况下在函数内使用 PHP 类方法? - How can I use PHP Class Method inside a function without using global variable? 使用curl,我如何从另一个网站(不同服务器)上的表单调用php类和类中的函数 - Using curl, how can i call a php class and a function inside the class from a form i have on another website (different server) 无法调用PHP类的方法 - Can not call method of the PHP class 我可以创建一个我可以在没有括号的情况下调用的PHP函数吗? - Can I create a PHP function that I can call without parentheses? php需要从inside方法调用类 - php require class call from inside method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM