CodeIgniter 定義“全局變量-global variable”,可以在所有controller,model和view中使用


本文抄自http://www.cnblogs.com/webu/archive/2012/11/20/2779999.html

 

   第一次正兒八經用CodeIgniter框架做項目,結果不會定義全局變量,只能在一個controller里定義一個public varable,每個函數調用,別的controller里還需要重新定義,view里還用不了,必須先傳值。

       經過研究,在CI中使用全局變量需要自定義Library的形式定義全局變量,這里我介紹一個用config里配置的方法

 

一:library/globals.php  

<?php if  ( ! defined( 'BASEPATH' )) exit ( 'No direct script access allowed' );
                          
class  Globals
{
                              
     function  __construct( $config  = array () ){
         foreach  ( $config  as  $key  => $value ) {
             $data [ $key ] = $value ;
         }
                          
         $CI  =& get_instance(); //這一行必須加
                          
         $CI ->load->vars( $data );
     }
}

 

二:/config/globals.php <-名字必須和library一致,定義具體變量

<?php if  ( ! defined( 'BASEPATH' )) exit ( 'No direct script access allowed' );
                 
$config [ 'globals_text' ] = "test text" ;
                 
$config [ 'globals_text1' ] = "test text11" ;

 

 

三:/config/autoload <-配置自動加載項,加載global library

/*
| -------------------------------------------------------------------
|  Auto-load Libraries
| -------------------------------------------------------------------
| These are the classes located in the system/libraries folder
| or in your application/libraries folder.
|
| Prototype:
|
|   $autoload['libraries'] = array('database', 'session', 'xmlrpc');
*/
       
$autoload [ 'libraries' ] = array ( 'globals' );

 

 

現在定義了兩個變量globals_text和globals_text1就可以在所有MVC中使用了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM