是否有另一种方法可以在 PHP 中以 Java 风格方式使用全局变量而不使用 global
关键字?
下面的例子是非常常见和简单的。我会使用 define
关键字来完成此操作,但正如您所看到的,变量是相互依赖的,我相信您无法使用 define
来实现这一点。
当然,在下面的示例中我收到了错误。
真的很期待这个问题的解决方案。在我看来,必须为我想要使用全局变量的函数编写一个 global
定义似乎是一种无效的解决方案,应该是一个更好的解决方案。
$BASE_URL = "mysite.com";
$PRODUCTS_URL = $BASE_URL . "/products";
$ABOUT_URL = $BASE_URL . "/about";
function foo() {
echo $BASE_URL;
}
最佳答案
I would do it with the define keyword, but as you can see, the varibales are dependent from each other, and I believe you can't achieve that with define.
不太正确,这会工作得很好 - 这就是我可能会采取的方法:
define('BASE_URL', "mysite.com");
define('PRODUCTS_URL', BASE_URL . "/products");
define('ABOUT_URL', BASE_URL . "/about");
请小心不要占用常量 namespace ,您可能想编写一个函数,也许是这样的(可以使用调整,只是一个示例):
function get_url($item = NULL, $include_base = TRUE)
{
$urls = array(
'base' => 'mysite.com',
'products' => '/products',
'about' => '/about',
);
$output = $include_base ? $urls['base'] : '';
if (isset($urls[$item])) $output .= $urls[$item];
return $output;
}
然后像 echo get_url('products');
那样调用它。只要在调用 foo() 时定义它,它就会起作用。我总是努力避免 global
或 $GLOBALS
。
关于PHP 全局关键字解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11172224/