在php中使用require或include函数时如何在函数内部调用变量

在php中使用require或include函数时如何在函数内部调用变量,php,Php,那么,我们可以使用require或include调用函数内部的变量,而不在函数中使用它吗 以下是示例代码: Include/Require文件(假设文件为“Include.php”) 索引文件 预期产出: 一些价值 另一个价值 全球使用是一种床上练习,但它会起作用 <?php $v1 = "foo"; $v2 = "bar"; function test(){ global $v1, $v2; echo $v1

那么,我们可以使用require或include调用函数内部的变量,而不在函数中使用它吗

以下是示例代码:

  • Include/Require文件(假设文件为“Include.php”)
  • 
    
  • 索引文件
  • 
    
    预期产出:

    一些价值 另一个价值


    全球使用是一种床上练习,但它会起作用

    <?php
      $v1 = "foo";
      $v2 = "bar";
     
     function test(){
        global $v1, $v2;
        echo $v1 . $v2;
     }
     
     test();
    

    使用include/require实际上与您的问题无关。include或require只会将其他文件的内容“合并”到您的代码中,以便可用

    正如其他人提到的,您需要使用
    global
    关键字。在许多其他编程语言中,默认情况下全局变量在函数中可见。但是在PHP中,您需要明确定义哪些变量应该在每个函数中可见

    例如:

    <?php  
        $a = "first";
        $b = "second";
        $c = "third";
    
        function test() {
            global $a, $b;
            echo $a . " " . $b . " " . $c;
        }
    
        test();   // This will output only "first second" since variable $c is not declared as global/visible in the test-function
    ?>
    

    不,include/require不改变变量范围在PHP中的工作方式。如果希望这些变量在函数的局部作用域中可用,则可以在函数内部要求该文件。最好的方法是使函数接受一个参数。阅读。@El_Vanja谢谢!!,使用
    global$var1
    全局$var2编码到函数中,它就可以工作了!!一条建议:除非您在整个应用程序中的大量函数中确实需要这些变量,否则请避免使用全局变量。如果在函数中需要变量值,请将其作为参数传递。跟踪和调试要容易得多。
    
    <?php
      $v1 = "foo";
      $v2 = "bar";
     
     function test(){
        global $v1, $v2;
        echo $v1 . $v2;
     }
     
     test();
    
    <?php  
        $a = "first";
        $b = "second";
        $c = "third";
    
        function test() {
            global $a, $b;
            echo $a . " " . $b . " " . $c;
        }
    
        test();   // This will output only "first second" since variable $c is not declared as global/visible in the test-function
    ?>
    
    <?php  
        define("A", "first"); 
        define("B", "second");
        define("C", "third");
    
        function test() {
            echo A . " " . B . " " . C;
        }
    
        test();   // This will output "first second third". You don't need to use the global keyword since you refer to global constants
    ?>