PHP新建類問題分析及解決思路
下面先給大家分析php新建類的問題
index.php文件
function __autoload($_className) {
require $_className.'.class.php';
}
//新建類??
if (isset($_GET['index'])) {
$m=new Main($_GET['index']);
}else{
$m=new Main();
}
include $m->ui();
main.class.php文件
class Main{ private $index; //構(gòu)造方法,初始化數(shù)據(jù) public function __construct($index=''){ $this->index=$index; } //ui函數(shù)include相應(yīng)的包含文件 public function ui(){ if(empty($this->index)||!file_exists($this->index.'.inc')){ $this->index='start'; } return $this->index.'.inc'; } }
紅字的部分有啥意義了:類中構(gòu)造函數(shù)傳參值已設(shè)默認(rèn)是空(public function __construct($index='')),為啥不能直接寫$m=new Main($_GET['index']);。如果不想在index做紅字的if判斷,類里需要怎么寫了。謝謝,不是太理解
------解決思路----------------------
if (isset($_GET['index'])) { $m=new Main($_GET['index']); //如果 $_GET['index'] 存在則將 $_GET['index'] 作為參數(shù) }else{ $m=new Main(); //否則使用默認(rèn)參數(shù) }
直接使用 $_GET['index'] 將可能引發(fā) NOTICE 級別錯誤
不加區(qū)別的使用傳入數(shù)據(jù),可能引發(fā)安全問題
------解決思路----------------------
稍微改了一下你看咋樣。
<?php class Main{ private $index; //構(gòu)造方法,初始化數(shù)據(jù) public function __construct($index='') { $this->index=$index?$index:''; } //ui函數(shù)include相應(yīng)的包含文件 public function ui() { if(empty($this->index)
------解決思路----------------------
!file_exists($this->index.'.inc')) { $this->index='start'; } return $this->index.'.inc'; } }
ps:php怎么創(chuàng)建文件?
php項目開發(fā)過程中,常常需要自動創(chuàng)建一些文件,如生成靜態(tài)html,生成php緩存文件,生成txt文件等等。下面就分享一下如何利用php程序創(chuàng)建文件,并向文件中寫入內(nèi)容。
一個項目中,可能不止一次需要生成文件,因此我們可以定義一個函數(shù),當(dāng)需要創(chuàng)建文件時再來調(diào)用這個函數(shù),即可。
步驟一、定義函數(shù)writefile,用于以寫的方式打開一個文件,文件不存在時自動創(chuàng)建,并向文件寫入內(nèi)容,代碼如下。
<?php function writefile($fname,$str){ $fp=fopen($fname,"w"); fputs($fp,$str); fclose($fp); } ?>
步驟二、函數(shù)的使用。如創(chuàng)建test.txt文件,并寫入內(nèi)容“abc”,代碼如下:
<?php $filename='test.txt'; $str='abc'; writefile($filename,$str); ?>
通過上述兩個步驟的操作,即可實現(xiàn)php創(chuàng)建文件的功能。
相關(guān)文章
destoon后臺網(wǎng)站設(shè)置變成空白的解決方法
這篇文章主要介紹了destoon后臺網(wǎng)站設(shè)置變成空白的解決方法,需要的朋友可以參考下2014-06-06PHP網(wǎng)頁游戲?qū)W習(xí)之Xnova(ogame)源碼解讀(八)
這篇文章主要介紹了PHP網(wǎng)頁游戲Xnova(ogame)源碼解讀的公共函數(shù)部分,需要的朋友可以參考下2014-06-06Laravel中獲取路由參數(shù)Route Parameters的五種方法示例
這篇文章主要給大家介紹了關(guān)于Laravel中獲取路由參數(shù)Route Parameters的五種方法,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Laravel具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起看看吧。2017-09-09