Is it necessary to use a global variable?
I am facing an issue regarding global variable
scope in p开发者_运维知识库hp. Below is my code snippet, can you tell me what am I doing wrong, and if the use of a global variable is unnecessary?
PHP version is 5.3.5
a.php
global $login;
$login = 0 ;
if(1==1) // here is some session checking condition
{
echo "<BR/>inside if".__FILE__;
$login = 1 ;
}
function alpha() {
echo "<BR/>".__FUNCTION__;
global $login;
if($login)
{
echo "<br/>Login is available";
}
else
{
echo "<br/>Login not available";
}
}
b.php
$login=0;
if(1==1) // same condition define in a.php
{
ECHO "<BR/>inside if".__FILE__;
$login = 1;
}
if($login == 0)
{
echo "out";
}
login.php
require_once("a.php");
require_once("b.php");
alpha();
echo "<BR/>".__FILE__;
echo $login;
It seems that my approach is wrong, what's a better method? Is declaring any variable global is necessary in this scenario? Will $login
in b.php
affect any variable?
note: if
condition in both a.php
and b.php
is same, but i can not combine.
Use functions or class based approach.
A simple function would be
function is_logged_in() {
static $login;
if (isset($login)) return $login;
$login = 0;
if (1 == 1) { // here is some session checking condition
$login = 1 ;
}
return $login;
}
Yes, I agree with Martin, you should try classes.
And I would like to add, that having this kind of separating logic into two files is wrong. If it is operation on $login, you should simply create class like "Login" and concentrate all decisions and operations regarding login (or user management generally) into that class. There is no reason to separate it into multiple files.
I hope I helped.
精彩评论