0

I just started learning PHP awhile ago and I am starting a new project. When I am trying to call a global varible it gives me an undefined variable error. I have had many people look over this code and no one seems to know the issue.

<?php
$UserID = 0;
$UserName = "Mark";
$TalkingToUserID = 1;
$TalkingToUserName = "Dalton";

$chatLog = fopen($UserID . "T" . $TalkingToUserID . ".txt", "w") or die("Unable to open file!");

function writeToFile($txt){
    fwrite($chatLog, "\n" . $txt);
    fclose($chatLog);
}
writeToFile("Hello");
?>

It's saying: Notice: Undefined variable: chatLog in Messenger.php on line 18 for all varibles I have declared.

Haley Mueller
  • 487
  • 4
  • 16
  • Where is the global variable? – pr1nc3 Nov 08 '17 at 14:26
  • PHP won't treat something as global simply because it was defined in global scope. To expose that global to the function call `global $chatLog;` inside the function body. But better would be to pass `$chatLog` to the function as an argument like `function writeToFile($txt, $chatLog)` – Michael Berkowski Nov 08 '17 at 14:27
  • 2
    Or just move the `fopen` line into the function, since the function is also closing the file. – aynber Nov 08 '17 at 14:27
  • PHP docs on variable scope: http://php.net/manual/en/language.variables.scope.php – Michael Berkowski Nov 08 '17 at 14:28

0 Answers0