PHP避免重複申明函數的解決方案_PHP教程

來源:互聯網
上載者:User
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
?> 現在,我們不再怕同時包含一個包多次或定義一個函數多次會出現的錯誤了。這樣直接帶給我們的好處是,維護我們的程式變得比較輕鬆了。

http://www.bkjia.com/PHPjc/532336.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/532336.htmlTechArticlePHP避免重複申明函數的解決方案jincoo(來自RUTED.COM的爬蟲) 我們知道,在PHP中不能使用相同的函數名定義函數兩次,如果這樣,程式執行的時...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.