Variable scope

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Variable scope

Post by Stryks »

Hi all.

Please excuse this possibly totally basic question, but I cant seem to find any info on the problem I'm having.

I've got one file (index.php) which includes two files. The first file holds some info regarding the loacation of files and so on, so that I can make changes later. They are set in that include file with :

Code: Select all

$STDB_USER = 'member_auth';
That is fine, and I can use it in index.php, but I was hoping I could also use it in the second included file.

I guess I sort of had this image of the included file being parsed as though it was a part of the file it was included from, hence putting it in the same scope.

Am I making sense? Is there any way of doing what I'm looking for?

Thanks
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

There's no problem with doing :
//file1.php
<?php
include_once 'inc1.php';
include_once 'inc2.php';
?>
//inc1.php
<?php
$test = 'hello';
?>
//inc2.php
<?php
echo $test;
?>

if that's what you mean?
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Post by Stryks »

Yeah, thats it exactly.

But it doesnt seem to work. If I echo the value then it is just blank.

Any ideas?
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Post by Stryks »

Ok, on second thoughts, thats not exactly it.

The second include file has a function which uses the variable established in include 1.

The function is then called from index.php

//file1.php
<?php
include_once 'inc1.php';
include_once 'inc2.php';

example();
?>

//inc1.php
<?php
$test = 'hello';
?>

//inc2.php
<?php
function example()
{
echo $test;
}
?>
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Post by Stryks »

Ahhh :)

//inc2.php
<?php
function example()
{
global $test
echo $test;
}
?>

That works
User avatar
dull1554
Forum Regular
Posts: 680
Joined: Sat Nov 22, 2003 11:26 am
Location: 42:21:35.359N, 76:02:20.688W

Post by dull1554 »

Roja
Tutorials Group
Posts: 2692
Joined: Sun Jan 04, 2004 10:30 pm

Post by Roja »

That has got to be the most completely useful and hilarious image I have seen on the net in my 10+ years here.

Thank you so much for that.. I will make great use of it on my forums.
User avatar
dull1554
Forum Regular
Posts: 680
Joined: Sat Nov 22, 2003 11:26 am
Location: 42:21:35.359N, 76:02:20.688W

Post by dull1554 »

i thought so
Post Reply