Search code examples
phpwarnings

PHP: Undefine variable when calling an object with in a function?


I get "Undefine variable" from the following code.

This is all the code from index.php

<?php
include "globals.classes.php";
$anObj = new Globals();
logout();

function logout() {
    echo $anObj->getName(); //Warning: Undefined variable $anObj
    exit();
}
?>

I know passing $anObj in the parameter will work,

but is it possible to make it work without passing it through parameter?

I want to call a function this way..

logout();

not this...

logout($anObj);


Solution

  • That's because $anObj is out of scope. You need to either make logout() a member of Globals() and invoque it as:

    <?php
    include "globals.classes.php";
    $anObj = new Globals();
    $anObj->logout();
    
    // In your class Global() you'll do something like this
    class Globals {
       function getName() {}
    
       function logout() {
        echo $this->getName();
        exit();
       }
    }
    ?>
    

    Another solution could be this:

    <?php
    include "globals.classes.php";
    $anObj = new Globals();
    echo $anObj->getName();
    logout()
    
    function logout() {
        exit();
    }
    

    In that case you won't need logout(). But I guess you might want to do a few more things than just an exit()