程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> PHP避免重復申明函數的解決方案

PHP避免重復申明函數的解決方案

編輯:關於PHP編程

PHP避免重復申明函數的解決方案jincoo(來自RUTED.COM的爬蟲) 我們知道,在PHP中不能使用相同的函數名定義函數兩次,如果這樣,程序執行的時候就會出錯。 而我們會把一些常用的自定義函數提取出來,放到一個Include文件中,然後別的文件就可以通過Include或require來調用這些函數,下面是一個例子:// 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.php和test2.inc.php中同時定義了fun1這個函數,我雖然知道這兩個函數實現的功能完全相同,但是我並不確定,或者說我不想明確的知道,一個函數是不是在某個“包”(INCLUDE)中定義了,另外的一個問題是,我們不能包含一個包兩次,但是我並不想在這裡花過多的時間進行檢查,上面的例子,執行test.php會產生很多錯誤。 在C語言中,提供了預定義功能可以解決這個問題:#ifndef __fun1__
#define __fun1__
// do any thing
#endif PHP並不提供這樣的機制,但是我們可以利用PHP的靈活性,實現和C語言的預定一同樣的功能,下面舉例如下:// 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
?> 現在,我們不再怕同時包含一個包多次或定義一個函數多次會出現的錯誤了。這樣直接帶給我們的好處是,維護我們的程序變得比較輕松了。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved