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



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

这是示例代码:

  1. 包含/要求文件(假设该文件是"Include.php"(
<?php
$var1 = "Some Value";
$var2 = "Another Value";
?>
  1. 索引文件
<?php
require 'include.php';
function test1(){
echo $var1;
}
function test2(){
echo $var2;
}
test1();
test2();
?>

预期输出:

某些值另一个价值

使用全局is床练习,但它将在中工作

<?php
$v1 = "foo";
$v2 = "bar";

function test(){
global $v1, $v2;
echo $v1 . $v2;
}

test();

另一个解决方案是使用设计模式注册表:

https://github.com/AnthonyWlodarski/Design-Pattern-Examples/blob/master/registry.php

include/request的使用实际上与您的问题无关。包含或要求将仅";合并";将其他文件的内容添加到您的代码中,以便变得可用。

正如其他人提到的,您需要使用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
?>

但是,如果变量应该被视为静态常量,我建议您将它们定义为常量。常数有一个";真实的";全局范围,并且不需要使用global关键字。

<?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
?>

最新更新