PHP中的范围可变问题 [英] Trouble with variable scope in PHP

查看:50
本文介绍了PHP中的范围可变问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的情况:

我正在开发一个PHP项目,该项目使用了一些我编写的用于与外部xml文档一起使用的功能.我想要做的是将相同的functions.php文件导入到许多都使用相同代码的不同页面中.问题在于xml文件的路径并不总是相同,并且通常取决于当前显示的视图.

I'm working on a PHP project that uses a few functions I have written to work with an external xml document. What I want to do is import the same functions.php file into many different pages that all use the same code. The problem is that the path to the xml file isn't always the same, and is often dependent upon the view that is currently displayed.

我想做的基本上是在我include 'path-to-functions.php';之前在我的视图中声明一个$source = 'path-relative-to-view';,然后让该函数在必要时访问$ source变量.这样,我就不必为我所在的每个不同目录重写函数.

What I am trying to do is basically declare a $source = 'path-relative-to-view'; in my view, before I include 'path-to-functions.php'; and then have the functions access the $source variable whenever necessary. In this way, I won't have to rewrite the functions for every different directory I am in.

我认为这是可行的,但是不幸的是,我还没有足够了解PHP.

I assume this is possible, but unfortunately, I haven't used PHP enough to know for sure.

推荐答案

您必须在将要使用的每个函数中声明$source全局变量.

You'll have to declare $source global in every function that'll use it.

function abc
{
    global $source;
    //--use $source
}

这篇关于PHP中的范围可变问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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