1

I've included a file in my php script, but for some reason, it can't read a variable I've declared globally, because including the file...

How I've arranged everything:

The include is inside a function

The variable is declared globally (note: even when I declare the variable one line before the include, it can't read the variable (this is in a function though))

The included file reads the variable from a function (in other words: the statement if ($errorcheckonly==true) {} is inside a function in the included file)

Could any of this have an influence on why it's not working?

Code example:

Main file:
$errorcheckonly = true; //declared here or declared beneath, not both
function processOrder() {
$errorcheckonly = true;
include 'passengersform.php'; //forced to only use error checks
}
processOrder();

Included file:
function processtickets () {
echo '<script language="javascript">alert("'.$errorcheckonly.'");</script>';
if ($errorcheckonly==true) { exit; }
}
processtickets();
2
  • 1
    Please show your code. If it is long, try to create a minimal example that reproduces your problem. You might find the solution by yourself while creating this example... :-) Commented Dec 3, 2011 at 20:12
  • That is the reason why I described the layout. But like you asked, I added a piece of code. :) Commented Dec 3, 2011 at 20:18

2 Answers 2

1

See this other example

<?php
    $var = 'test' ;

    function A ( ) {
        global $var ;

        echo $var ;
    }   

    A ( ) ;

The output is test

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

5 Comments

I now have declared $errorcheckonly outside any function, used global $errorcheckonly; to read it in both the function in the main file as in the function in the included file, thanks!
Is it also possible to declare a global variable from a function, without declaring it outside that function?
Ah ok, too bad I can't do global variable = value; but I guess I can live with that, haha
THank you very much for your help once again!
Nopz .. the other way its store data in a session.
1

See this simple example

<?php
function A ( ) {
    global $var ;
    $var = 'test' ;
}

A ( ) ;

function B ( ) {
    global $var ;
    echo $var ;
}   

B ( ) ;

4 Comments

Isn't a variable global by default when I declare it outside a function?
@laarsk No. Read the php docs for more on variable scope (php.net/manual/en/language.variables.scope.php)
No, but either way, you'll have to use global $ var within the function that will define the scope for you
Wow. This is an eye opener for me. Really because I've done similar things before, and it always worked perfect for me... Also, would I have to use global to read the variable? Now that's weird. (However, very handy aswell, as you can now have duplicate variables?)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.