如何在一个函数中保存全局变量数据并在另一个函数中回显它们

时间:2017-11-22 22:53:17

标签: php global-variables

这是我的问题。我正在尝试创建一个大文件(完整的函数),它将调用对象函数。我想创建一些SUPERGLOBAL变量,它将包含有关该类(甚至在函数之间)类的所有内容,例如" user"。什么数据?就像用户的ID,名称,电子邮件,数据库中的级别一样,所以我不需要在此文件的几乎每个函数中使用USERS的SQL SELECT。

这就是我的core.php文件的样子(仅仅是为了解释我想要做什么)

//File -- core.php
require_once "pdo.php"; //Includes the $db -- pdo connection to database
require_once "user.php"; //Including the object
$GLOBAL["user"] = new USER($db);

function login($email, $pswd){
  $GLOBAL["user"]->login($email, $pswd); //LOGIN and also in this class function are written the data like $GLOBAL["user"]->ID, etc
  //do something more
}

function ShowLoggedUser(){
   echo $GLOBAL["user"]->ID; //But now here it's not working -> it's empty, nothing there
   echo $GLOBAL["user"]->Email;
   //etc

}

事情是,我在对象USER中设置了公共数据,如

//file -- user.php
class USER
{
    //Public data

    public $Name;
    public $Level;
    public $ID;
    public $Email;

    private $DB;

    function __construct($DB_con)
    {

      $this->DB = $DB_con;      
    }
    public function login ($email, $password)
    {
      //Some SQL and verifying user with DB
      //if everything is ok do this:
      foreach($result as $data){ //Results from SQL -- details about user
        $this->ID = $data["ID"];
        $this->Name = $data["Name"];
        $this->Email = $data["Email"];
      }
      return "some message";
    }

函数Login是这个文件的关键,如果登录不被使用,则用户被踢出这个文件(它的文件仅供登录用户使用),所以有100个%保证写出了课堂上的数据,当我在函数" login"中回显它们时它们真的出现了。但在其他任何地方它都是空的......

感谢您提供任何帮助/提示!

0 个答案:

没有答案