Web lists-archives.com

[PHP] How Do I make Global Scope Variables Available to Functions

I am writing a PHP script that has a number of variables that (I think) are in
Global scope; that is, they are defined inline before the first command of the
script.  Note that these are not necessarily constants as shown in the example I
included; most of them can be changed by the script.

I have functions defined following these variables and before the commands in
the script appear, but when they are called, the functions report the variables
as undefined.  This means I have to pass all the Globals to each function as a
call argument.  

A trivial script illustrating the problem is below.

This seems odd but I don't see what I am doing wrong.  Any suggestions?

PHP 5.6.30 called through php-fpm on Apache.

Thanks in advance.

test.php - working version

This variant passes a variable in global scope explicitly as a parameter.  It
displays correctly on the browser screen.


$bad_line = "This line should display on screen.";

// sample function that works
function sample1($bad_line)
 return "\n" . $bad_line . "\n";

// this call does work
echo sample1($bad_line);


test.php - doesn't work

This variant does not work; it throws error:

[Sun May 27 20:17:46.779348 2018] [proxy_fcgi:error] [pid 893:tid
139838497978112] [client] AH01071: Got error 'PHP message:
PHP Notice:  Undefined variable: bad_line in /httpd/iliffe/yrarc/test.php on
line 8\n'


$bad_line = "This line should display on screen.";

// sample function that doesn't work
function sample1()
 return "\n" . $bad_line . "\n";

//  this call doesn't work
echo sample1();



PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php