简体   繁体   English

PHP,两个外部脚本上的全局变量

[英]Php, global variables on two external scripts

How would I pass a global var in two external scripts? 如何在两个外部脚本中传递全局变量?

<div>
<!-- INCLUDEPHP 1.php -->
</div>
<div>
<!-- INCLUDEPHP 2.php -->
</div>

I have tried creating global variables on 1.php and `2.phpp but it didn't work. 我试过在1.php和`2.phpp上创建全局变量,但是没有用。

1.php: 1.php:

<?php
global $someVar;
$sql = ...;
$someVar= $db -> sql_query($sql);
?>

2.php: 2.php:

<?php
global $someVar;
echo "$someVar";
?>

Am I doing something wrong? 难道我做错了什么?

I would try including the scripts via PHP: 我会尝试通过PHP包含脚本:

<div>
<?php require "1.php" ?>
</div>
<div>
<?php require "2.php" ?>
</div>

If both includes are loaded into the same page, and the variables exist already in the global scope, all your functions can access them with the global statement. 如果将两个include都加载到同一页面中,并且变量已经存在于全局范围内,则所有函数都可以使用global语句访问它们。 Since everything is already global, the statement is not required in the global scope, only inside functions. 由于所有内容都已经是全局的,因此在全局范围内不需要该语句,而仅在函数内部。 This also permits functions to share variables by casting them onto the global scope. 这也允许函数通过将变量转换为全局范围来共享变量。

There are many dangers to this, though, which I'll not pretend to be fully aware of, so one is best advised to make prudent use of the global scope in large complex applications as they can become very volatile if naming conventions are relaxed. 但是,这样做有很多危险,我不会假装没有完全意识到,因此,最好在大型复杂应用程序中谨慎使用全局范围,因为如果放宽命名约定,它们会变得非常不稳定。

Basically, we're looking at, 基本上,我们正在研究

function arrow() { global $a; $a = "arrow"; return $a; }
function sky() { global $b; $b = "sky"; return $b; }
echo "I shot an " . arrow() . " into the " . sky() . ".";
echo "I shot an $a into the $b.";

which is child's play, it demonstrates how exposed the variables are, sitting out there with no protection. 这是儿童游戏,它演示了变量的暴露程度,没有保护就坐在那里。 Now another function can come along and blow the whole thing apart: 现在可以引入另一个函数,将整个过程分解开:

function whammo() { global $a, $b; $c = $a; $a = $b; $b = $c;}
echo "I shot an " . arrow() . " into the " . sky() . ".";
whammo();
echo "I shot an $a into the $b.";

See what I mean? 明白了吗?

Your solution probably lies in a closure of some sort, wherein all the functions are contained that need this 'global'. 您的解决方案可能在于某种形式的闭包,其中包含需要此“全局”的所有功能。 It will be much better protected. 它将得到更好的保护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM