PHP 5 - 跨包含文件的变量范围,没有类或函数 [英] PHP 5 - Variable scope across include files with no classes or functions

查看:31
本文介绍了PHP 5 - 跨包含文件的变量范围,没有类或函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了很多关于这个的话题,但仍然无法理解它.

这是我的基本问题:

header.php 包含一个名为 navigation.php 的文件.在navigation.php 中,定义了$previous$next.使用 echo 语句,我已验证它们具有值.

接下来,header.php 包含一个名为 backnext.php 的文件.我需要 backnext.php 来知道 $previous$next 的值.如果我在 backnext.php 的顶部将它们声明为 global,我不会收到错误,但是 echo 语句显示它们是空的.如果我不这样做,我会收到 undefined variable 错误.

我到底需要在哪里将它们声明为 global 才能让 backnext.php 能够正确读取它们的值?

这些文件都没有使用函数或类.

解决方案

如果这些文件都没有函数或类,那么 $prev$next 在全局中范围,并且应该被所有包含文件看到,并且您不需要使用 global 关键字.

听起来您的包含顺序可能有点错误.

更新:

如果我理解正确的话,你有这样的事情:

header.php:

navigation.php:

backnext.php:

如果我运行这个,我得到:

<前>在 header.php 中在导航.php退出 navigation.php在 backnext.php 中上一个=你好世界#1下一个=你好世界#2退出 backnext.php也可以在 header.ph 中看到上一个=你好世界#1下一个=你好世界#2

backnext.php 可以看到 $prev$next.

I've read through many, many threads on this and still can't wrap my head around it.

Here's my basic issue:

header.php includes a file called navigation.php. Within navigation.php, $previous and $next are defined. Using echo statements I have verified they have values.

Next, header.php includes a file called backnext.php. I need backnext.php to know the values of $previous and $next. If I declare them as global at the top of backnext.php, I don't get errors, but echo statements show they are empty. If I don't, I get an undefined variable error.

Where exactly do I need to declare them as global to have backnext.php be able to read their values correctly?

None of these files are using functions or classes.

解决方案

If none of these files have functions or classes then $prev and $next are in the global scope and should be seen by all your include files and you shouldn't need to use the global keyword.

It sounds like the order of your includes may be a bit wrong.

Update:

If I understand correctly you have something like this:

header.php:

<?php
echo "In header.php\n";

require_once("navigation.php");
require_once("backnext.php");

echo "Also seen in header.php:\n";
echo "prev=$prev\n";
echo "next=$next\n";
?>

navigation.php:

<?php
echo "In navigation.php\n";
$prev = "Hello World#1";
$next = "Hello World#2";
echo "Exiting navigation.php\n";
?>

backnext.php:

<?php
echo "In backnext.php\n";
echo "prev=$prev\n";
echo "next=$next\n";
echo "Exiting backnext.php\n";
?>

If I run this I get:

In header.php
In navigation.php
Exiting navigation.php
In backnext.php
prev=Hello World#1
next=Hello World#2
Exiting backnext.php
Also seen in header.ph
prev=Hello World#1
next=Hello World#2

backnext.php is able to see both $prev and $next.

这篇关于PHP 5 - 跨包含文件的变量范围,没有类或函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆