php claims my defined variable is undefined

后端 未结 4 1947
北海茫月
北海茫月 2020-12-19 03:27

My php is a little rusty but this is boggling my mind right now. I googled this and read all the stackoverflow questions I could find that looked related, but those all seem

相关标签:
4条回答
  • 2020-12-19 03:52
    <?php
    $msgs = "";
    
    function add_msg($msg){
      global $msgs;
      $msgs .= "<div>$msg</div>";
    }
    function print_msgs(){
      global $msgs;
      print $msgs;
    }
    
    add_msg("test");
    add_msg("test2");
    print_msgs();
    ?>
    

    global tells that PHP need to use the global variable in the local function scope.

    0 讨论(0)
  • 2020-12-19 04:00

    Using globals for something like this is a poor practice. Consider an alternate approach such as the following:

    class MessageQueue {
      private static $msgs;
    
    
      public static function add_msg($msg){
        self::$msgs .= "<div>$msg</div>"; 
      }
      public static function print_msgs(){
        print self::$msgs;
      }
    }
    
    
    MessageQueue::add_msg("test");
    MessageQueue::add_msg("test2");
    MessageQueue::print_msgs();
    
    0 讨论(0)
  • 2020-12-19 04:04

    It's defined at the global scope. Use global if you want to use it.

    0 讨论(0)
  • 2020-12-19 04:06

    if you don't want to use globals, you can jast use

     function add_msg($msg)
       {
             echo  "<div>$msg</div>";
       }
        add_msg("test");
        add_msg("test2");
    

    function, the result will be the same.

    0 讨论(0)
提交回复
热议问题