如何在MVC项目中使用php类中的全局变量


how to use global variables in php class in a MVC project

我想在mvc项目中的模型类中的函数中$st_id,如下所示,但它给我带来了一个错误,即$st_id没有定义。我能做些什么来解决这个问题?

<?php
@session_start();
$st_id=$_SESSION['username'];
if (!isset($_SESSION['USERNAME']))
{
header('Location: signin.php');
}
//////////////////////    
class model
{
    private $result;
    public $rp_result;
    //////////
    public function exe_query()
    {
        $mysqldb = new MySQLDatabase();
        $result=$mysqldb->query('CALL view_report('.$this->st_id.');');
        $this->rp_result=$mysqldb->fetch_all($result);
    }
}   
?>

如何调用您的模型?

我建议你:

class model
{
    private $result;
    public $rp_result, $st_id;
    public function __construct($st_id)
    {
        $this->st_id = $st_id;
    }
    public function exe_query()
    {
        $mysqldb = new MySQLDatabase();
        $result=$mysqldb->query('CALL view_report('.$this->st_id.');');
        $this->rp_result=$mysqldb->fetch_all($result);
    }
}

现在,您可以使用:

@session_start();
$st_id=$_SESSION['username'];
if (!isset($_SESSION['USERNAME']))
{
    header('Location: signin.php');
}
$model = new model($st_id);
$model->exe_query();

如果将其与$this 一起使用,则必须在类中声明它

class model {
    public $st_id;
    public function __construct() {
        @session_start();
        $this->st_id = $_SESSION['username'];
    }
    public function exe_query()
    {
        $mysqldb = new MySQLDatabase();
        $result=$mysqldb->query('CALL view_report('.$this->st_id.');');
        $this->rp_result=$mysqldb->fetch_all($result);
    }
}

为什么不直接将其称为$_SESSION['username']?它已经是全球性的。。。