Page 1 of 1

Global variables & includes / functions

Posted: Tue Aug 23, 2005 8:33 pm
by chandldj
Hi there... as you'll see i'm a newbie :)

I have a function in an include and i'd like to make some of the variables usable in the main page...

say i have 2 pages index.php and include.php as follows...


index.php
------------

<?
include $root."include.php";

getvar();

?>

blah blah blah

<? echo $a; ?>



-------------------------------------

include.php
--------------

<?

function getvar();
{
$a = "my global variable";
}
?>

-------------------------------------

how can i make $a a callable variable in index.php without making it a session variable???
i tried setting it as a global variable in the include file, but nogo both inside and outside of the getvar() function.

Thanks in advance for your help!

I would use a class

Posted: Tue Aug 23, 2005 10:38 pm
by raymondkwoods
Fairly new to php myself but I would use a class as follows:

include.php
--------------

Code: Select all

<?php
 class myClass {
   var $a;

   function myClass($a) {
      $this->a = $a;
   }

   function getVar() {
      return $this->a;
   }

   function setVar($a) {
      $this->a = $a;
   }
}
?>
Then just instantiate an instance of the class for each variable you want. All operations you perform on the variable can be carried out in member functions within the class. That way everything is self contained.
Example:

index.php
------------

Code: Select all

<?php
include "test.php";

$testClass = new myClass("my member variable");

echo $testClass->getVar();
?>
You also should not have a semi-colon on the line function getvar();. If you don't want to mess around with classes then you can just do the following:

include.php
-------------

Code: Select all

<?php
function getvar()
{ 
   $a = "my global variable";
   return $a;
} 
?>
index.php
------------

Code: Select all

<?php
include "test.php";

echo getVar();
?>
You can't call $a directly from another file because you are declaring the variable within a function which means that it is local to that function (as soon as the function ends the variable dies along with it).

Hope this helps
:D

Posted: Tue Aug 23, 2005 10:39 pm
by anjanesh
Your $a in getvar() function is local and gets destroyed once the function is done with.

Instead in index.php have

Code: Select all

$a = getvar();
and in include.php have

Code: Select all

function getvar();
 {
 return "my global variable";
 }

thanks :)

Posted: Wed Aug 24, 2005 2:42 am
by chandldj
Thanks for your input guys :)

I wasn't looking to get the variable back through the function... there's a number of functions in the include, but one of them contains several mysql commands that i can use throughout the site...

Anyway, it was solved by...

$GLOBALS['a'] = $a;

in the function in the include file, then just calling

$GLOBALS['a'] in the index.php file.