将PHP变量传递给包含的文件? [英] Passing PHP variables to an included file?

查看:139
本文介绍了将PHP变量传递给包含的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该有用,所以我真的很困惑为什么它不起作用。

This should work, so I'm really perplexed about why it's not working.

我正在检查用户是否使用$ session登录每个管理页面顶部的类方法。但是,我想根据用户是否登录以及用户具有的角色级别动态调整头文件。

I'm checking to see if a user is logged in using a $session class method at the top of each admin page. However, I want to dynamically adjust the header file depending on whether a user is logged in, and on what role level that user has.

所以我检查 $ session-> is_logged_in()然后我继续并定义了一个名为 $ logged = true 的变量;以后再用然后我使用 $ user-> find_by_id($ session-> id)方法创建一个新的User对象并存储 $ user-> ; role_level 在一个名为 $ role_level 的新var中,以方便使用。

So I check $session->is_logged_in() and then I went ahead and defined a variable called $logged = true; to use later. I then use a $user->find_by_id($session->id) method to create a new User object and store $user->role_level in a new var called $role_level for easy use.

这是一切都发生在页面顶部附近。在页面的下方经过表格处理等,是 include(../_ layouts / header.php)命令。然后,在header.php文件中,我使用像 if(!$ logged){...} else {...} 之类的小支票。但是......

This is all happening near the top of the page. Further down the page past form processing, etc., is the include("../_layouts/header.php") command. Then, in the header.php file, I use little checks like if(!$logged) { ... } else { ... }. However...

我收到以下错误:

Notice: Undefined variable: logged in /home/hips/html/_layouts/header.php on line 119
Notice: Undefined variable: logged in /home/hips/html/_layouts/header.php on line 131
Notice: Undefined variable: logged in /home/hips/html/_layouts/header.php on line 138

这怎么可能?在我包含header.php之前,我正在定义文件中的变量!那应该不行吗?

How can this be? I'm defining the vars in the file before I include header.php! Shouldn't that work?

仅供参考,一切正常,直到我尝试在header.php文件中使用 $ logged

FYI, everything was working fine until I tried to use $logged in the header.php file.

推荐答案

变量会传播到包含的文件,所以必须是,当变量未设置时你调用include:尝试检查是否如此,然后弄清楚为什么变量没有设置在那一点。

Variables do propagate to the included files, so it must be, that the variable is NOT set when you call the include: try checking if so, then figure out why is the variable not set at that point.

例如,如果你在if中定义了$ logged 阻塞或在函数内部,然后它不会传播到它之外:你必须在最外层的范围内定义它(在你调用include语句的同一级别)。并且您必须为用户未登录的情况定义它,而不仅仅是在用户登录的情况下。如果变量未初始化为false,则检查是否(!$ logged)将发出警告。假设$ logged = false;在你工作的开始。

For example, if you defined $logged inside the "if" block or inside a function, then it won't propagate outside of it: you must define it in the outermost scope (at the same level at which you call the include statement). And you must define it for the case that the user is not logged in, not only for the case when the user is logged in. If the variable is not initialized to false, the check if(!$logged) will issue warning. Say $logged = false; at the beginning of your work.

这篇关于将PHP变量传递给包含的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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