Page 1 of 1

scope issue

Posted: Fri Jan 24, 2003 11:17 am
by iamzek
I admit that I"m rather new at this ... but not to programming ... and this is confusing me...

in the following the fist echo statment yeilds "chaos" --- this is good ... the second yeilds "=" or a char similar --- this is confusing as it's global ... or am I missing something? ( code snipped )

Code: Select all

<?php

include './lib/stdhtml.php';
include './lib/sec.php';

global $db_name;
$db_name = "chaos";

htmlheader();

echo '$db_name = '.$db_name."<BR>";

function main()&#123;

echo 'main start $db_name = '.$db_name."<BR>";
// code
&#125;


function Auth( $argp = 0 )&#123;

	echo "<form Action='db_setup.php?cmd=start' Method=post>
	";

	if ( $argp ) &#123; echo "<TR><TD align=center>Unable to locate username/password combination</TD></TR>"; &#125;
	else &#123; $username = ''; &#125;

	echo '
	<TR><TD align=center>Username: <input type"textbox" Value="'.$username.'" name=user_name></TD></TR>
	<TR></TR><TR><TD align=center>Password: <input type"password" name=password></TD></TR>
	<TR><TD><input type=submit>"  "<input type="reset"></TD></TR>
	</FORM>';

&#125;

htmlfooter();

switch($_REQUEST&#1111;'cmd'])&#123; 

    case "start":
    main();
    break;

    default:
    Auth();
    break;

&#125;
thanks

Posted: Fri Jan 24, 2003 12:09 pm
by volka
global is a scope of it's own and functions cannot access it by default (since all their variables are created in the function's scope)
To have access to a global scope var from within a function you have to mark it as global, e.g.

Code: Select all

$db_name = 'Chaos';
function test()
{
	global $db_name;
	echo $db_name; // without global the lookup for $db_name would be in test's scope
	$db_name = ' something else';
}
test();
echo $db_name;
There are superglobals that need no extra scoping to access them from anywhere. the array/hash $GLOBALS is one of them and is available since php3.
http://www.php.net/manual/en/language.v ... .scope.php
http://www.php.net/manual/en/reserved.variables.php