thinkphp的c方法使用樣本

來源:互聯網
上載者:User

 用過thinkphp的朋友都知道,C()方法在整個架構中用的非常普遍,C方法的實現非常簡單,但是功能非常強大,下面是C()方法的詳解和使用樣本

1.C方法的作用 a. 載入設定使用者的配置,儲存在一個C函數內的靜態變數$_config 中 b. 讀取使用者的配置 (從$_congig 中讀取) 2. 需求分析: 1.設定變數 1.二維數組代碼如下:C(array('DB_PASSWORD'=>'root','DB_USERNAME'=>'root'),'DB'); C('DB.USER_NAME','XIAOCHEN);   2.一維數組  代碼如下:C('USER_NAME','小陳'); C(array('USER_NAME'=>'chen','USER_HEIGHT'=>'170'));   2.讀取變數  一維:   C('USER_NAME'); 二維:  C('DB.DB_PASSWORD'); 3.調試時,查看所有的配置資訊 C(); 3.存放方式及為什麼要這樣儲存? 首先我們來看一個問題$arr=array('db'=>'mysql','DB'=>'mysql','Db'=>'mysql'); 從這個數組我們可以看到db都是指向了mysql,但是在卻佔用了三個存放空間,在項目的開發不是由一個人完成,每個人的書寫習慣可能不一樣,所以為了避免這種情況,統一的下標轉為小寫(當然大寫也是可以的),由於設定檔在中的數組只有最多隻有二維,把一維數組的下標小寫就夠了 4.實戰中是怎麼用的? php由於對數組的操作非常便捷,所以設定檔一般是寫在一個設定檔中,以數組的形式返回 一般格式為:    代碼如下:config.php<?  return array('DB'=>'mysql',......);   把變數寫入到C中  :  C(include 'config.php');     寫入後C('DB') 就可以擷取值了 5.筆者寫的  (新增動態添加二維配置的功能) 代碼如下: C(array('name'=>'mysql','password'=>'root'),'db') 執行後array('db'=>array('name'=>'mysql','password'=>root))  程式碼範例:  代碼如下:function C($name=null,$value=null){  static $_config = array();   if(!is_null($name)){    if(is_string($name)){     if(is_null($value)){      if(!strpos($name,'.')){       $name = strtolower($name);       return isset($_config[$name]) ? $_config[$name] : null;       }else{       $name = explode('.',$name);       $name[0] = strtolower($name[0]);       return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : null;      }     }else{      if(!strpos($name,'.')){       $_config[strtolower($name)] = $value;      }else{       $name = explode('.',$name);       $_config[strtolower($name[0])][$name[1]] = $value;      }      return ;     }    }elseif(is_array($name)){     if(is_null($value))      $_config = array_merge($_config,$name);     else{      $_config[$value] = $name;     }     return ;    }   }else{       return empty($_config) ? null: $_config;  }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.