手册 >> 开发指南 >> dump变量调试

dump变量调试

dump变量调试是在PHP框架日常开发中最常用的调试手段,开发者应善用dump调试工具,以提高开发效率。

dump变量调试可以测试一切PHP变量,下面举几个常用的例子:

排错案例

<?php
class main extends spController
{

	function index(){
		$tpl = $this->spArgs('tpl','default'); // 接收tpl参数作为显示的模板名称,默认是default
		if( $tpl = 'green' ){
			// 当模板是绿色的时候
			$this->title = "绿色模板";
		}else{
			// 当模板是默认的时候
			$this->title = "默认模板";
		}
		$this->display($tpl.'.html');
	}

}
?>

以上的代码运行后,我们发现无论输入的tpl值是否green,都是显示green的模板,这是为什么呢?

我们在display之前加入dump来看看$tpl的值。

<?php
class main extends spController
{

	function index(){
		$tpl = $this->spArgs('tpl','default'); // 接收tpl参数作为显示的模板名称,默认是default
		if( $tpl = 'green' ){
			// 当模板是绿色的时候
			$this->title = "绿色模板";
		}else{
			// 当模板是默认的时候
			$this->title = "默认模板";
		}
		dump($tpl);
		$this->display($tpl.'.html');
	}

}
?>

发现$tpl一直都是'green',那么我们再在多个位置dump($tpl);看看。

<?php
class main extends spController
{

	function index(){
		$tpl = $this->spArgs('tpl','default'); // 接收tpl参数作为显示的模板名称,默认是default
		dump($tpl); // 提交参数没问题
		if( $tpl = 'green' ){
		
			dump($tpl); // 绿色?
		
			// 当模板是绿色的时候
			$this->title = "绿色模板";
		}else{
		
			dump($tpl); // 默认?
		
			// 当模板是默认的时候
			$this->title = "默认模板";
		}
		dump($tpl);
		$this->display($tpl.'.html');
	}

}
?>

最终发现,是在IF判断的位置,$tpl值被改变了,把“=”改为“==”,运行程序正常。

<?php
class main extends spController
{

	function index(){
		$tpl = $this->spArgs('tpl','default'); // 接收tpl参数作为显示的模板名称,默认是default
		if( $tpl == 'green' ){
			// 当模板是绿色的时候
			$this->title = "绿色模板";
		}else{
			// 当模板是默认的时候
			$this->title = "默认模板";
		}
		$this->display($tpl.'.html');
	}

}
?>

通常,IF中使用双等号的时候,要注意是否写少了一个等号。有个推荐的编程习惯,就是把IF内的判断式调转一下位置,值在前变量在后。如上例中写成if( 'green' == $tpl ),那么即使写错为“=”,$tpl也不会被赋值,这样更容易判断出问题所在,不会被$tpl的取值影响。在框架的多个例子中到有这种写法。

检查提交参数

在接收到提交参数后,通常我们可以dump一下全部的提交参数出来看看,检查表单提交的数据是否和理想中一样。

dump($this->spArgs());

入库前检查

在数据入库之前,我们通常可以dump一下将入库的数据出来看看是否正确。

		$row = array(
			'username' => 'jake',
			'contents' => '大家好',
			'ctime' => date('Y-m-d H:i:s'),
		);
		dump($row); // 看看入库的数据是否是正确的。
		//spClass('m_guestbook')->create($row); // 先注释入库代码,dump检查后没问题再入库