php - 如何使用另一个 php 文件中的变量

标签 php mysql

我知道有人问过类似的问题,但不幸的是我在经历过这些问题后未能解决问题。

假设这种情况:在 one.php 中,我从输入字段检索一些数据并将其保存为变量,稍后我需要 Two.php

one.php

$rejon = $_POST['rejon'];

require 'two.php';

two.php

--here I would like to use $rejon ---

当我尝试在two.php中使用$rejon时,它不起作用(确切地说,我尝试将其插入数据库)。另一方面,如果我不需要 Two.php 而是将代码粘贴到 one.php 中,它就可以工作。

我不明白为什么会发生这种情况。 W3schools 声称“include(或 require)语句获取指定文件中存在的所有文本/代码/标记,并将其复制到使用 include 语句的文件中。” -http://www.w3schools.com/php/php_includes.asp

但它似乎不像副本一样工作,因为手动复制会给出其他结果(变量 $rejon 是可访问的)。

1) require 到底做什么以及它的局限性是什么? 2)最重要的是 - 如何在two.php中检索$rejon变量?

最佳答案

对我有用:

$ cat one.php
<?php
$rejon = 'this value came from POST';
require 'two.php';

$ cat two.php
<?php
echo $rejon . PHP_EOL;

$ php one.php
this value came from POST

W3Schools 描述为 unsurprisingly , 误导。没有任何内容被复制。文件的内容在 require 处被读取、评估和插入。关于变量,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.

这就是为什么我上面的例子能够正常工作。

要诊断此问题,请继续简化代码,将其简化为最简单的示例。如果您尝试在两个函数内的函数中使用$rejon,那么您需要将该变量设置为全局变量。喜欢:

global $rejon;
$rejon = $_POST['rejon'];
// now you have $GLOBALS['rejon'] everywhere

附注,除非您跨越页面刷新边界,否则不需要 $_SESSION

关于php - 如何使用另一个 php 文件中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25286906/

相关文章:

php - 我的 php 脚本显示结果已删除,但 phpmyadmin 仍显示结果

php - 具有 rtmp 格式的 JW 播放器的动态 XML 播放列表。

php - 如何从一个 inner-join-where 查询中将获取的结果显示到 2 组不同的 div 中?

mysql - 合并两行mysql

php - 使用 idiorm 从 mysql 获取以特殊字符开头的数据

mysql - ShoreTel MySQL 查询

php - 连接 PHP 源代码并将表单提交到 MySQL 数据库

php - mysql_fetch_row() : supplied argument is not a valid MySQL result resource in

java - mysql和tomcat导致服务器过载

java - 来自数据库的 jfreechart 散点图