1

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);

2
  • 2
    Using logout($anObj); (besides using classes) is a much more common and recommended way of solving this problem. So I would recommend getting used to it rather than how can I get round it. Commented Dec 17, 2022 at 10:13
  • 1
    What Nigel Ren wrote. There are other ways, but it requires you to read the manual thought and then your understanding. One context might be variable scope: php.net/manual/en/language.variables.scope.php - Keep in mind that some variables are much more expensive than others: The more broad their scope is, the more they are a dependency of all that scope, regardless in use or not. This is why the point that Nigel Ren commented is that important, it allows you to reduce the scope and therefore the cost. Commented Dec 17, 2022 at 10:21

1 Answer 1

1

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()

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.