PHP新建类问题分析及解决思路
(编辑:jimmy 日期: 2025/11/10 浏览:3 次 )
下面先给大家分析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;
//构造方法,初始化数据
public function __construct($index=''){
$this->index=$index;
}
//ui函数include相应的包含文件
public function ui(){
if(empty($this->index)||!file_exists($this->index.'.inc')){
$this->index='start';
}
return $this->index.'.inc';
}
}
红字的部分有啥意义了:类中构造函数传参值已设默认是空(public function __construct($index='')),为啥不能直接写$m=new Main($_GET['index']);。如果不想在index做红字的if判断,类里需要怎么写了。谢谢,不是太理解
------解决思路----------------------
if (isset($_GET['index'])) {
$m=new Main($_GET['index']); //如果 $_GET['index'] 存在则将 $_GET['index'] 作为参数
}else{
$m=new Main(); //否则使用默认参数
}
直接使用 $_GET['index'] 将可能引发 NOTICE 级别错误
不加区别的使用传入数据,可能引发安全问题
------解决思路----------------------
稍微改了一下你看咋样。
<"htmlcode">!file_exists($this->index.'.inc')) { $this->index='start'; } return $this->index.'.inc'; } }ps:php怎么创建文件"htmlcode">
<"w"); fputs($fp,$str); fclose($fp); } "htmlcode"><?php $filename='test.txt'; $str='abc'; writefile($filename,$str); ?>通过上述两个步骤的操作,即可实现php创建文件的功能。
下一篇:php有效防止同一用户多次登录