将包含数据的局部变量设置为全局格式

时间:2017-08-08 08:48:09

标签: php codeigniter

我有这个变量包含if语句中数据库的数据。如何将其设置为全局或有没有办法在if语句之外访问这些数据?

if(condition){
   $data = G_Employee::find()->single('id', 'some value'); 
} 

2 个答案:

答案 0 :(得分:0)

使用此句法访问该if语句之外的数据

$GLOBALS['data'];
     if(condition){
       $data = G_Employee::find()->single('id', 'some value'); 
    } 

答案 1 :(得分:0)

您可以为您的班级定义变量,并使用/ $this

进行访问

示例:

class MY_CLASS extends CI_Controller {

   protected $data;

   public function MY_FUNCTION {
      if(condition){
         $this->data = G_Employee::find()->single('id', 'some value'); 
      }

      var_dump($this->data); //$this->data is accessible from anywhere in your class. 
                            //You can check if it has the value you want
   }

}