PHP 类中的外部变量访问
考虑以下情况
文件:./include/functions/table-config.php 包含:
.
.
$tablePages = 'orweb_pages';
.
.
文件:./include/classes/uri-resolve.php 包含:
class URIResolve {
.
.
$category = null ;
.
.
function process_uri() {
...
$this->category = $tablePages;
...
}
.
.
}
文件:./settings.php 包含:
.
.
require_once(ABSPATH.INC.FUNC.'/table-config.php');
require_once(ABSPATH.INC.CLASS.'/uri-resolve.php');
.
.
Will this work. I mean will the access to $tablePages from process_uri() be acceptable or will it give erronous results.如果可能出现错误,请提出更正或解决方法。
Consider the following situation
file: ./include/functions/table-config.php
containing:
. . $tablePages = 'orweb_pages'; . .
file: ./include/classes/uri-resolve.php
containing:
class URIResolve { . . $category = null ; . . function process_uri() { ... $this->category = $tablePages; ... } . . }
file: ./settings.php
containing:
. . require_once(ABSPATH.INC.FUNC.'/table-config.php'); require_once(ABSPATH.INC.CLASS.'/uri-resolve.php'); . .
Will this work. I mean will the access to $tablePages from process_uri() be acceptable or will it give erronous results.
Please suggest corrections or workarounds if error might occur.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用全局关键字:
在您要分配的文件中价值。
在另一个文件中:
此外,所有全局变量都可以在
$GLOBALS
数组中使用(它本身就是一个超全局变量),因此您可以在任何地方访问全局变量,而无需使用 global 关键字,方法如下: this:这也使得意外覆盖全局值变得更加困难。 在前一个示例中,您对
$tablePages
所做的任何更改都会更改全局变量。 许多安全错误是由于拥有全局$user
并用更强大的用户信息覆盖它而产生的。另一种更安全的方法是将构造函数中的变量提供给 URIResolve:
Use the global keyword:
In the file where you're assigning the value.
And in the other file:
Also, all global variables are available in the
$GLOBALS
array (which itself is a superglobal), so you can access the global variable anywhere without using the global keyword by doing something like this:This also serves to make it harder to accidentally overwrite the value of the global. In the former example, any changes you made to
$tablePages
would change the global variable. Many a security bug has been created by having a global$user
and overwriting it with a more powerful user's information.Another, even safer approach is to provide the variable in the constructor to URIResolve:
使用全局(不推荐)、常量或单例配置类。
简单地包含
将为您的变量提供局部范围,因此它在其他类中不可见。 如果使用常量:
TABLE_PAGES 将可用于整个应用程序的读取访问,无论范围如何。
常量相对于全局变量的优点是您不必担心它在应用程序的其他区域被覆盖。
Use a global (not recommended), a constant or a singleton configuration class.
Simply including
will give your variable local scope so it won't be visible inside other classes. If you use a constant:
TABLE_PAGES will be available for read access throughout the application regardless of scope.
The advantage of a constant over a global variable is that you dont have to worry about it being overridden in other areas of the application.