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

WBOY
Release: 2016-06-13 12:42:01
Original
986 people have browsed it

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

<? <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);}
Copy after login


如果把 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);}
Copy after login

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template