PHP call_user_func vs. just calling function

前端 未结 8 1549
我寻月下人不归
我寻月下人不归 2020-12-04 08:06

I\'m sure there\'s a very easy explanation for this. What is the difference between this:

function barber($type){
    echo \"You wanted a $type haircut, no         


        
相关标签:
8条回答
  • 2020-12-04 08:56

    in your first example you're using function name which is a string. it might come from outside or be determined on the fly. that is, you don't know what function will need to be run at the moment of the code creation.

    0 讨论(0)
  • 2020-12-04 08:57

    There is no benefits calling the function like that because I think it mainly used to call "user" function (like plugin) because editing core file is not good option. here are dirty example used by Wordpress

    <?php
    /* 
    * my_plugin.php
    */
    
    function myLocation($content){
      return str_replace('@', 'world', $content);
    }
    
    function myName($content){
      return $content."Tasikmalaya";
    }
    
    add_filter('the_content', 'myLocation');
    add_filter('the_content', 'myName');
    
    ?>
    

    ...

    <?php
    /*
    * core.php
    * read only
    */
    
    $content = "hello @ my name is ";
    $listFunc = array();
    
    // store user function to array (in my_plugin.php)
    function add_filter($fName, $funct)
    {
      $listFunc[$fName]= $funct;
    }
    
    // execute list user defined function
    function apply_filter($funct, $content)
    {
      global $listFunc;
    
      if(isset($listFunc))
      {
        foreach($listFunc as $key => $value)
        {
          if($key == $funct)
          {
            $content = call_user_func($listFunc[$key], $content);
          }
        }
      }
      return $content;
    }
    
    function the_content()
    {
      $content = apply_filter('the_content', $content);
      echo $content;
    }
    
    ?>
    

    ....

    <?php
    require_once("core.php");
    require_once("my_plugin.php");
    
    the_content(); // hello world my name is Tasikmalaya
    ?>
    

    output

    hello world my name is Tasikmalaya
    
    0 讨论(0)
提交回复
热议问题