Trouble with variable scope in PHP

2019-09-19 08:49发布

问题:

Here's my situation:

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.

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.

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

回答1:

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

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


回答2:

You could use a global variable - but don't, global variables aren't good.

Just rewrite the functions to take the path to the file as one of their parameters.

Another thing you can do is group them inside of a class. Then use a member variable of the class to store the path which they will all be able to access.