Home >Backend Development >PHP Tutorial >为何调用函数时必须把数据库连接文件放在函数体里面

为何调用函数时必须把数据库连接文件放在函数体里面

WBOY
WBOYOriginal
2016-06-13 11:29:18740browse

为什么调用函数时必须把数据库连接文件放在函数体里面
像下面这个程序:

<? <br />header("Content-type: text/html; charset=gb2312"); <br /><br />  $act=$_GET["act"];<br /><br />if($act=="del")	{		 	//删除记录<br />	$id =$_GET["id"];<br />	require('conn.php');<br />	$conn->query("delete from lyb where id=$id");<br />	fy();	}<br /><br />if($act=="list") { fy();}<br /><br />function fy() {<br />require('conn.php');<br /> $sql="select * from lyb order by ID desc";<br />	//echo $sql;<br /><br />$result=$conn->query($sql);}


如果把 require('conn.php');写在函数的外面就不行,如下所示。这样如果有几个if语句的话,require('conn.php');就要重复写几遍,很不方便。我记得无参无返回值的函数,其实就相当于把该函数体中的代码插入到调用函数的位置处,但从这里看并不是这样的哦。

<? <br />header("Content-type: text/html; charset=gb2312"); <br />require('conn.php');<br />  $act=$_GET["act"];<br /><br />if($act=="del")	{		 	//删除记录<br />	$id =$_GET["id"];<br />	$conn->query("delete from lyb where id=$id");<br />	fy();	}<br /><br />if($act=="list") { fy();}<br /><br />function fy() {<br /> $sql="select * from lyb order by ID desc";<br />	//echo $sql;<br /><br />$result=$conn->query($sql);}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn