下面先給大家分析php新建類的問題
index.php文件
1
2
3
4
5
6
7
8
9
10
|
function __autoload( $_className ) { require $_className . '.class.php' ; } <span style= "color: #ff0000" > //新建類?? if (isset( $_GET [ 'index' ])) { $m = new Main( $_GET [ 'index' ]); } else { $m = new Main(); </span>} include $m ->ui(); |
main.class.php文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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判斷,類里需要怎么寫了。謝謝,不是太理解
------解決思路----------------------
1
2
3
4
5
|
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ā)安全問題
------解決思路----------------------
稍微改了一下你看咋樣。
1
2
3
4
5
6
7
8
9
10
11
12
|
<?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) |
------解決思路----------------------
1
2
3
4
5
6
7
|
! 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)容,代碼如下。
1
2
3
4
5
6
7
|
<?php function writefile( $fname , $str ){ $fp = fopen ( $fname , "w" ); fputs ( $fp , $str ); fclose( $fp ); } ?> |
步驟二、函數(shù)的使用。如創(chuàng)建test.txt文件,并寫入內(nèi)容“abc”,代碼如下:
1
2
3
4
5
|
<?php $filename = 'test.txt' ; $str = 'abc' ; writefile( $filename , $str ); ?> |
通過上述兩個步驟的操作,即可實現(xiàn)php創(chuàng)建文件的功能。