Page 1 of 1

Problem in Accessing Variable value across php files

Posted: Sun Nov 08, 2009 5:15 am
by ankit_sam
Hi,
As the title says it all.
Problem in Accessing Variable value across php files.
I have two .php files.
I have simplied the code to give as an example.

here is the code of both php

functions.php

Code: Select all

<?php
 
function getValue()
{
$a=10;
}
?>
index.php

Code: Select all

<?php
require_once('functions.php')
getValue();
echo $a;
?>
Now, when i execute, 10 shuld be printed?
if not then how to do it.
because i have 4 variables in functions.php

Re: Problem in Accessing Variable value across php files

Posted: Sun Nov 08, 2009 5:30 am
by requinix
The problem isn't that you're using two files: the problem is about variable scope. Read this.

If you have a variable inside a function, and you want to access it outside the function, make the function return it. More information.

Code: Select all

function getValue()
{
    $a=10;
    return $a;
}

Code: Select all

require_once('functions.php')
$a=getValue();
echo $a;

Re: Problem in Accessing Variable value across php files

Posted: Sun Nov 08, 2009 6:04 am
by ankit_sam
Thanks :)