PHP避免重复申明函数的解决方案

来源:互联网 发布:新誉网络 编辑:程序博客网 时间:2024/05/21 09:34
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

 

   我们知道,在PHP中不能使用相同的函数名定义函数两次,如果这样,程序执行的时候就会出错。

   而我们会把一些常用的自定义函数提取出来,放到一个Include文件中,然后别的文件就可以通过Includerequire来调用这些函数,下面是一个例子:

<?PHP
//   File name test1.inc.PHP

function fun1()
{
 // do any fun1
}

function fun2()
{
 // do any fun2
}
?>

<?
//   File name test2.inc.PHP

require("test1.inc.PHP");

function fun1()
{
 // do any fun1
}

function fun3()
{
 // do any fun3
}
?>

<?
//   File name test.PHP
//可能需要包含其他的文件
require("test1.inc.PHP");
require("test2.inc.PHP");
// do any test
?>

   test1.inc.PHPtest2.inc.PHP中同时定义了fun1这个函数,我虽然知道这两个函数实现的功能完全相同,但是我并不确定,或者说我不想明确的知道,一个函数是不是在某个”(INCLUDE)中定义了,另外的一个问题是,我们不能包含一个包两次,但是我并不想在这里花过多的时间进行检查,上面的例子,执行test.PHP会产生很多错误。

   C语言中,提供了预定义功能可以解决这个问题:

#ifndef __fun1__
#define __fun1__
// do any thing
#endif

   PHP并不提供这样的机制,但是我们可以利用PHP的灵活性,实现和C语言的预定一同样的功能,下面举例如下:

<?PHP
//   File name test1.inc.PHP

if ( !isset(____fun1_def____) )
{
 ____fun1_def____ = true;
  function fun1()
 {
   // do any fun1
 }
}
if ( !isset(____fun2_def____) )
{
 ____fun2_def____ = true;
 function fun2()
 {
   // do any fun2
 }
}
?>

<?
//   File name test2.inc.PHP

require("test1.inc.PHP");

if ( !isset(____fun1_def____) )
{
 ____fun1_def____ = true;
 function fun1()
 {
   // do any fun1
 }
}
if ( !isset(____fun3_def____) )
{
 ____fun3_def____ = true;
 function fun3()
 {
   // do any fun3
 }
}
?>

<?
//   File name test.PHP
//可能需要包含其他的文件
require("test1.inc.PHP");
require("test2.inc.PHP");
// do any test
?>

   现在,我们不再怕同时包含一个包多次或定义一个函数多次会出现的错误了。这样直接带给我们的好处是,维护我们的程序变得比较轻松了。<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击