dongmu5920 2016-08-22 08:55
浏览 15

函数可以在PHP中的函数声明和函数定义之前使用吗? [关闭]

I've never seen this type of scenario in PHP. Most of the PHP examples and tutorial use the format of function calling after the declaration, but here i tried it for the first time.I think PHP use interpreter and read the code line by line. should not it generate an error in line 3 when it has not detect any function declaration before line 3?

      <?php
      $m=new m;
      echo $m->abd(17,18);
       class m
       {
           function abd($a,$b)
           {
            return($a+$b);
            }
       }
      ?>

But Output was

35

is this Possible? For reference this is the Sandbox Link you can try this code

</div>
  • 写回答

1条回答 默认 最新

  • dongqian3198 2016-08-22 08:58
    关注

    From the PHP Manual

    Functions need not be defined before they are referenced, except when a function is conditionally defined as shown in the two examples below.

    However, it just seems like good practice to define your functions before you use them

    Those two examples are

    <?php
    
    $makefoo = true;
    
    /* We can't call foo() from here 
       since it doesn't exist yet,
       but we can call bar() */
    
    bar();
    
    if ($makefoo) {
      function foo()
      {
        echo "I don't exist until program execution reaches me.
    ";
      }
    }
    
    /* Now we can safely call foo()
       since $makefoo evaluated to true */
    
    if ($makefoo) foo();
    
    function bar() 
    {
      echo "I exist immediately upon program start.
    ";
    }
    
    ?>
    

    And

    <?php
    function foo() 
    {
      function bar() 
      {
        echo "I don't exist until foo() is called.
    ";
      }
    }
    
    /* We can't call bar() yet
       since it doesn't exist. */
    
    foo();
    
    /* Now we can call bar(),
       foo()'s processing has
       made it accessible. */
    
    bar();
    
    ?>
    

    For more information, this answer is sources from another SO answer

    评论

报告相同问题?