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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Setting a varialbe from another file?

Status
Not open for further replies.

k3bap

Programmer
Jul 9, 2003
8
GB
Hi I have an include file config.inc.php and another file.

I am trying to set a variable within the config.inc.php from the other file. Is this possible?

Doesnt seem to work!
 
Hi sleipnir214, thanks but thats not what I meant.

From your example, I am looking for a way to set $foo from test.php so that it updates in test.inc!

Is that possible?
 
ok, I have the variable declared in

test.inc:
<?php
$foo = '10'
?>


What I want to do is Increment it but the code to do that MUST be in test.php

In other words i am trying to MODIFY a global variable in test.inc from test.php

I tried this

test.inc:
<?php
$foo = '10'
?>

test.php:
<?php
include ('test.inc');
$foo++;
echo ($foo);
?>

THis gives me the incrememnted value BUT it seems to copy the variable and make it local to test.php becuase when I use another file to access the varialbe like this:



test2.php:
<?php
include ('test.inc');
echo ($foo);
?>

I get the original value of 10 rather than 11. Does it make sense?

Thanks!



 
Sure. PHP is behaving as it should.

A variable only exists within the run of a single script. Once the script ends its run, the variable no longer exists. You run the second script, a new variable is created, it's value is set to 10, then incremented.

Unless you write the code to modify test.inc, the variable is always going to be set to 10. There is no automatic mechanism in PHP to modify the include file to reflect changes in the variable's value.

If you want to preserve a variable's value between scripts, and if you are using a web browser as your user interface, then you can use session variables to store values. Take a look here:
Want the best answers? Ask the best questions: TANSTAAFL!!
 
Take a look at this code:

test.php:
Code:
<?php
session_start ();
include ('test.inc');
print $_SESSION['foo'];
?>

test.inc:
Code:
<?php
if (!array_key_exists('foo', $_SESSION))
{
	print &quot;Initializing foo: &quot;;
	$_SESSION['foo'] = 10;
}
else
{
	print &quot;Incrementing foo: &quot;;
	$_SESSION['foo']++;
}
?>

Want the best answers? Ask the best questions: TANSTAAFL!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top