PHP Function include() Behavior

software development

#1

Hello, In writing one of my first webpages using PHP I quicky saw the benifit of using the ‘include’ function. I can’t figure out how this function behaves or is parsed. I hope someone might be able to help me on this.

ISSUE: I was under the assumption that using the ‘include’ function would be like adding the code to where you use the function call, but I’m getting results that show me otherwise.

On each page for my site I need data from a database to be displayed. It will be in the same format on each page like a header. I use a cookie to keep the username and password which is verified on each page to pull the datatbase information.

Lets say the webpage I’m on is ‘main.php’ and my ‘include’ file is ‘functions.php’.
The variable ‘$HTTP_COOKIE_VARS[username];’ apparently is visible to ‘main.php’ but ‘NULL’ in ‘functions.php’ so I have to pass the variable as an argument to ‘functions.php’. Why is this?

Also, I added the following assignment to ‘functions.php’
$field_num = 13; but it isn’t visble to functions in ‘functions.php’ and appears to be ‘NULL’.

The two PHP books don’t shed any light to my question but just state what I thought about the function just inserting code. I hope someone can help me.

Thanks,
Brian


#2

In the on-line PHP manual,

[quote]
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.[/quote]

If you are calling include() inside a function, then you have to declare $HTTP_COOKIE_VARS to be global, either in the function or in the included file.

You might want to use $_COOKIE instead, which is a superglobal and works in any scope.