3

I am facing an issue regarding global variable scope in php. 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.

hakre
  • 178,314
  • 47
  • 389
  • 754
diEcho
  • 50,018
  • 37
  • 156
  • 230
  • 1
    I would not recommend to use global variables see: http://stackoverflow.com/questions/1557787/are-global-variables-in-php-considered-bad-practice-if-so-why – Book Of Zeus Oct 15 '11 at 12:58
  • @BookOfZeus I know it is dangerous. but tell me what can be altered?? – diEcho Oct 15 '11 at 13:45

2 Answers2

3

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;
}
Petah
  • 42,792
  • 26
  • 149
  • 203
0

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.

graywolf
  • 5,904
  • 6
  • 39
  • 65
  • i dont do these silly coding. this is one of my client , he instruct not to change the coding but only design. during integrating with design.i stuck with this issue that user once logged in and when we go to inner pages or refresh the home page then it automatically logged out. because he set `$logic=0` then `session_unset()` . – diEcho Oct 16 '11 at 10:24