如何跨两个文件访问一个变量


How to access a variable across two files

我有三个文件-global.php, test.phptest1.php

Global.php

$filename;
$filename = "test";

test.php

$filename = "myfile.jpg";
echo $filename;

test1.php

echo $filename;

我可以通过以下方式从test和test1文件中读取此变量include 'global.php';

现在我想在test.php中设置$filename的值,并在test1.php. 中读取相同的值

我也尝试过使用会话变量,但由于有两个不同的文件,我无法捕获该变量。

如何实现。。。。。。。。

感谢您提前提供的帮助。。。。。

使用:

global.php

<?php
if(!session_id()) session_start();
$filename = "test";
if(!isset($_SESSION['filename'])) {
    $_SESSION['filename'] = $filename;
}
?>

test.php

<?php
if(!session_id()) session_start();
//include("global.php");
$_SESSION['filename'] = "new value";
?>

test1.php

<?php
if(!session_id()) session_start();
$filename = $_SESSION['filename'];
echo $filename; //output new value
?>

我认为理解这一点的最佳方式如下:
您有一个文件index.php,其中定义了一些变量。

$indexVar = 'sometext';

该变量在所有index.php文件中都可见。但与函数一样,如果包含其他文件,则除非指定该变量具有全局作用域,否则该变量将不可见。

您应该在新文件中重新定义此变量的范围,如下所示:

global $indexVar;

然后,您可以像在主文件中那样直接调用它来访问。你可以用一个";回声;在这两个文件中,index.php和任何其他文件。

首先从页面顶部开始会话。

将变量分配到会话中。

检查这个并尝试你自己的

test.php

<?php
session_start(); // session start
include("global.php");
$filename = "myfile.jpg";
$_SESSION['samplename']=$filename ; // Session Set
?>

test1.php

<?php
session_start(); // session start
$getvalue = $_SESSION['samplename']; // session get
echo $getvalue;
?>