开发者

PHP undefined variable

For the following code:

line 10: echo "before require: ".$test; 
line 11: require( dirname(__FILE__) . 'load.php' );
line 12: echo "after require: ".$test; 

The output:

before require: 
Notice: Undefined variable: test in /home/test.php on line 12
after require:

If load.php is very simple, there will be no message: "Notice: undefined variable....". Why and how "load.php" will affect $test variable?开发者_JAVA技巧


If the $test variable is unset inside load.php file.

That will effect your $test variable and you will be shown Notice: Undefined variable.

because variables declared before the include statement will be available inside the included file so any action performed on the variable inside that included file will affect that variable.


Your variable is not set, hence the notice message.

If you set a value to the variable $test in load.php, it will have that value.

If you don't, well ... it would stay undefined in your case, not a good practice.


From the documentation:

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. However, all functions and classes defined in the included file have the global scope.


Shouldn't it be require( dirname(__FILE__) . '/load.php' );? :)

Anyway, it looks like you either unset() variable in load.php, or modify display_errors and/or error_reporting to higher level in load.php.


If you have configured PHP to show all notices, warnings,and errors,you will see a notice when you run this script: Notice: Undefined variable: testing in /path/to/testtype.php on line 3 Notices are turned on by default when you use the php-development.inirather than php-production.ini,and can be very helpful when debugging scripts.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜