Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

global statement doesn't work 1

Status
Not open for further replies.

sen5241b

IS-IT--Management
Sep 27, 2007
199
US
The global statement works just fine on my server in this code:

main1.php:
Code:
<?php
include "call1.php";
$a = 1;
$b = 2;
Sum();
echo $b;
?>

call1.php:
Code:
<?php
function Sum()
{
    global $a, $b;
    $b = $a + $b;
} 
?>

But global does not work in a much bigger, more complex program. I tried the global statement at the beginning of the bigger program and it still does not work. (Definitely not a typo).

What would keep global from working in one program but not another on the same server?
 
Why not pass $a and $b into the Sum function as arguments and return the result? That would be a much more robust way of doing it.
Code:
<?php
  include "call1.php";
  $a = 1;
  $b = 2;
  echo Sum($a, $b);
?>
Code:
<?php
  function Sum($a, $b) {
    return ($a + $b);
  }
?>

Clive
Runner_1Revised.gif

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"To err is human, but to really foul things up you need a computer." (Paul Ehrlich)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To get the best answers from this forum see: faq102-5096
 
global is a misunderstood key word. you cannot declare a variable to be global using the global keyword. using it in the global scope has no effect at all.

what global does, in effect, is to bring a variable that is in the global scope (i.e. declared outside a function or class) and make it available to the scope of the function or class method in which the keyword is called.

if you want to have a properly global variable you need to use the $GLOBALS array. (or one of the other superglobals, like $_SESSIONS).
 
Thx! But I understand the scope aspect of global. I am trying to make a var in the main function available in a smaller called function.

I did try

Code:
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];

but this did not work either.

(Stretchwickster, the code was an example. My problem is in a much bigger program that I won't ask people here to read through).
 
it's hardly credible to assume that global keyword is broken on your system. if you do post your code we may be able to help.
 
You're absolutely right jpadie, but every once in a while there is a special, unusual rule for a standard PHP function. Or maybe I think I understand scope! Let me pare the code down some and post here. thx!
 
This first script just accepts a text string using an HTML form statement, you can ignore it. I provide it here just in case you want to run the whole thing.

Code:
<html>
<body>

<style type="text/css">
h1 {font-size: 800%}
h2 {text-align: center; color: red; font-size: 300%}
h3 {font-size: 200%}
h4 {text-align: center; font-size: 120%}
h5 {text-align: center; font-size: 120%}
p {font-size: 100%}
h3 {font-family: times}

h2.pos_left
{

}
h2.pos_right
{
position:relative;
left:20px
}

div.figureleft {
  float: left;
  width: 25%;
  border: thin red solid;
  padding: 0.5em;  }

IMG.displayed {
    display: block;
    margin-left: auto;
    margin-right: auto }

  #clearbreak {
	clear: both; }

	</style>



<title>Enter Test String</title>
<meta http-equiv=Copyright content="Tiger Crane Entertainment - 2007">
<meta name=rating content="14 years">
<meta name="description" content="Test Bad Word Filter">
<meta name="keywords" content="bad word, mind of scott">
<meta name="robots" content="index,nofollow">

<body bgcolor="#33CCCC" lang=EN-US link=red vlink=purple style='tab-interval:
.5in'>

<H2> The Mind of Scott </H2>

<H4> Enter text </H4>

<H4>
<form action="DetectOWs2-b.php" method="post">
<span style="position: relative; LEFT: -20.5px">  Comment:  &nbsp; 
<input type="text" 	 name="checkstr" 	id="checkstr" value="" size="120" tabindex="1" >
<BR><BR>
<input type="hidden" name="lowestsev" 	id="lowestsev" value="1" tabindex="2" >  
<input type="hidden" name="quickcheck" 	id="quickcheck" value="0" tabindex="3" > 
<input type="submit" VALUE="Test" />
 </span>
 </form>
</H4>

</body>
</html>

This is the main script where the variable $checkstr is first used. It calls a function in another PHP script where global is used.

Code:
<?PHP
echo ' super begin -------  well? lowestsev=';
	var_dump($_POST["lowestsev"]);
	echo 'well? quickcheck=';
	var_dump($_POST["quickcheck"]);
	echo 'well? checkstr=';
	var_dump($_POST["checkstr"]);
if (DetectOWs($_POST["checkstr"], $_POST["lowestsev"], $_POST["quickcheck"]))
			{
			echo '<B>' . "ERROR 66 BW - Wait for redirect." . '</b>';
			}   
echo 'jus afore func';
exit();

function DetectOWs($checkstr = " ", $lowestsev = "1", $quickcheck = "1") 
  {   
  include_once "ObsceneCleanLib-b.php";
  AccidentalOW("fred", 8);	// CALL FUNC AND TRY TO USE GLOBAL!!!
  echo ' $checkstr=' . $checkstr; 	// DISPLAYS STRING JUST FINE !!
  echo ' $lowestsev=' . $lowestsev;
  }
  ?>

In this PHP script function the global statement just don't work!!!!!

Code:
<?PHP
/* ========================================================================================================== */

function AccidentalOW($checkme, $position)
{
	global $checkstr;
	echo '<br>';
	$input = $checkstr;
	echo 'down in AccidentalOW ---------------!!!!!!!!!!!!!!!!';
	echo '<br> this displays NULL on my server: $input=';
	var_dump($input);
	echo '<br>';
}
?>
 
jpadie said:
it's hardly credible to assume that global keyword is broken on your system.

apologies. i wrote that post after a decent bottle of wine last night. even though i'm a lawyer, i'm not usually that pompous!

i'll take a look at your code and post back.
 
so the reason why this is not working is that $checkstr has never been in the global scope. its scope is the function detectOW().

the normal way of sorting this out is to pass the value to the accidentalOW function directly as an argument. you could also pass it by reference.

alternatively you will need to declare it to be global in scope in detectOW and then declare it to be global in accidentalOW. BUT... declaring the variable in the the arglist and then declaring it to be global in detectOW will, essentially, overwrite the value that is inserted through the arglist as the global keyword will, in essence, implicitly create a global version of the variable with a null value (as no existing variable exists in the global scope with the same name) - sorry that's a bit convoluted but i'm sure you get the idea).


so... if you really want to go down this route something like this will work

Code:
function DetectOWs($[red]_[/red]checkstr = " ", $lowestsev = "1", $quickcheck = "1") {   
	global $checkstr;
	$checkstr = $_checkstr;
	include_once "ObsceneCleanLib-b.php";
	AccidentalOW("fred", 8);    // CALL FUNC AND TRY TO USE GLOBAL!!!
	echo ' $checkstr=' . $checkstr;     // DISPLAYS STRING JUST FINE !!
	echo ' $lowestsev=' . $lowestsev;
}

but this isn't good practice. it is better to reference directly the superglobal $_POST in each case that you need to use the value in an unaltered state. It is NOT good practice to manipulate the values of the superglobal. at that point you should declare a holding array and manipulate the values in that.

another observation: your function does not return any value and yet you are testing it with a conditional. i suspect that the conditional will always fail. in 'old' Pascal/Ada type terms you should make sure that your functions (as opposed to subroutines) always return something via the return keyword.

lastly, you may find these debug functions useful as a generic set of debug functions. I've not tested them as i can't find the versions that i habitually use ;-(

Code:
/**
 * function to dump the superglobals to the screen for a debug
 * 
 * @return void 
 */
function debugSuperGlobals(){	
	$a = array('POST','GET','COOKIES','SESSION');
	foreach($a as $global){
		foreach($_{$global} as $key=>$val){
			echo '<pre>';
			echo "$key \t $val \r\n";
			echo "</pre>";
		}
		echo "<hr/>";
	}
}
/**
 * generic function to display debug messages
 * 
 * @return void 
 * @param $message string
 * @param $var Object
 * @example
 * debugMessage('Value just before executing function at line ' . __LINE__, $variable);
 */
function debugMessage ($message, $var){
	$output =  <<<HTML
<div style="color:green; width: 70%; border:black solid thin; font:courier;">
$message
<pre>
OUTPUT
</pre>
</div>
HTML;
	if (is_array($var) || is_object($var)){
		$t = print_r($var, true); 
	}
	if (is_bool($var)){
		$t = $var === true ? 'True' : 'False';
	}
	if (is_resource ($var)){
		$t = 'Resource';
	}
	if (is_null($var)){
		$t = 'NULL';
	}
	$_t = '$var' . " is $t";
	$output =  str_replace('OUTPUT', $_t, $output);
	echo $output;
}


 
Drinking and programming -- the scourge of the nation!

seriously, thx! I understand.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top