note 55595 modified in language.variables.scope by danbrown
| From: | danbrown@php.net | Date: | Mon, 18 May 2009 01:37:44 +0000 |
| Subject: | note 55595 modified in language.variables.scope by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-155565@lists.php.net to get a copy of this message | ||
Be careful with "require", "require_once" and "include" inside
functions. Even if the included file seems to define global variables, they might not be defined as
such.
consider those two files:
---index.php------------------------------
<?php
function foo() {
require_once("class_person.inc");
$person= new Person();
echo $person->my_flag; // should be true, but is undefined
}
foo();
?>
---class_person.inc----------------------------
<?php
$seems_global=true;
class Person {
public $my_flag;
public function __construct() {
global $seems_global;
$my_flag= $seems_global
}
}
?>
---------------------------------
The reason for this behavior is quiet obvious, once you figured it out. Sadly this might not be
always as easy as in this example. A solution would be to add the line...
<?php global $seems_global; ?>
at the beginning of "class_person.inc". That makes sure you set the global-var.
best regards
tom
ps: bug search time approx. 1 hour.
--was--
Be careful with "require", "require_once" and "include" inside
functions. Even if the included file seems to define global variables, they might not be defined as
such.
consider those two files:
---index.php------------------------------
function foo() {
require_once("class_person.inc");
$person= new Person();
echo $person->my_flag; // should be true, but is undefined
}
foo();
---class_person.inc----------------------------
$seems_global=true;
class Person {
public $my_flag;
public function __construct() {
global $seems_global;
$my_flag= $seems_global
}
}
---------------------------------
The reason for this behavior is quiet obvious, once you figured it out. Sadly this might not be
always as easy as in this example. A solution would be to add the line...
global $seems_global;
at the beginning of "class_person.inc". That makes sure you set the global-var.
best regards
tom
ps: bug search time approx. 1 hour.
http://php.net/manual/en/language.variables.scope.php