如何使用包含的 php 文件中的 php 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5483759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use php variables from an included php file
提问by dave
I have these variables that are set in one php file, and when i include that php file in another php file, how do i use those variables from the included php file?
我在一个 php 文件中设置了这些变量,当我将该 php 文件包含在另一个 php 文件中时,如何使用包含的 php 文件中的这些变量?
回答by Ben
They should just roll over:
他们应该翻身:
File1.php
文件1.php
<?php
$var1 = "TEST";
?>
File2.php
文件2.php
<?php
include("File1.php");
echo $var1; //Outputs TEST
?>
回答by Aron Rotteveel
Have you actually triedit?
你真的试过了吗?
Just usethe variables. They are available within the scope of the including file.
只需使用变量。它们在包含文件的范围内可用。
From the PHP manual:
从PHP 手册:
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.
当一个文件被包含时,它包含的代码继承了包含发生所在行的变量范围。从那时起,调用文件中该行可用的任何变量都将在被调用文件中可用。但是,包含文件中定义的所有函数和类都具有全局作用域。
回答by Michael J.V.
When you include one file in another, everything is visible from both of them. Imagine them as having one file, so you use the variables the regular way - by typing their name out.
当您将一个文件包含在另一个文件中时,所有内容都可以从这两个文件中看到。把它们想象成有一个文件,所以你可以以常规方式使用变量 - 通过键入它们的名称。