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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18588972/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:51:54  来源:igfitidea点击:

How to access a variable across two files

phpglobal-variablesstatic-variablesfile-access

提问by user2688512

I have three files - global.php,test.php, test1.php

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

Global.php

全局.php

$filename;
$filename = "test";

test.php

测试文件

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

test1.php

测试1.php

echo $filename;

echo $filename;

I can read this variable from both test and test1 files by include 'global.php';

我可以从 test 和 test1 文件中读取这个变量 include 'global.php';

Now i want to set the value of $filenamein test.phpand the same value i want to read in test1.php.

现在我想设置$filenamein的值test.php和我想读入的相同值test1.php.

I tried with session variables as well but due to two different files i am not able to capture the variable.

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

How to achieve this........

如何实现这一点......

Thanks for help in advance.....

提前感谢您的帮助......

回答by MaxEcho

Use:

用:

global.php

全局.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

测试1.php

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

回答by Nathan Srivi

First you start session at the top of the page.

首先,您在页面顶部开始会话。

Assign your variable into your session.

将您的变量分配到您的会话中。

Check this and Try it your self

检查这个并自己尝试

test.php

测试文件

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

test1.php

测试1.php

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