0

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
  • Sorry if I misunderstand. What you are saying is that your functions are generic enough but you have a hard coded $source? Commented Nov 1, 2011 at 4:24

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This is exactly the path I would take: First, writing the method signatures to include the parameters, then, if need be, classing it up. Not passing the method sig rewriting and going straight to classing it up is nice, as it removes the need to repetitiously pass the source as a parameter. It is just create, set, and start firing funcs.
can I ask why global variables are so bad?
It's not that they're 'bad', per-se. It's more that the drawbacks outweight the benefits - usually by a large margin.
1

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

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

1 Comment

Even if it isn't recommended, its definitely something I should know how to use. I was having a hard time understanding the documentation on how to use it, but I guess I just needed one sentence from you! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.