Trouble with variable scope in PHP

佐手、 提交于 2019-12-11 16:50:20

问题


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.



来源:https://stackoverflow.com/questions/7962332/trouble-with-variable-scope-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!