


PHP solution to avoid repeated declaration of functions_PHP tutorial
Jul 13, 2016 pm 05:22 PM
PHP's solution to avoid repeatedly declaring functions jincoo (crawler from RUTED.COM) We know that you cannot use the same function name to define a function twice in PHP. If so, an error will occur when the program is executed. We will extract some commonly used custom functions and put them into an Include file. Then other files can call these functions through Include or require. Here is an example: // 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
//Possibly Need to include other files
require("test1.inc.php");
require("test2.inc.php");
// do any test
?> in test1.inc The fun1 function is defined in both .php and test2.inc.php. Although I know that these two functions implement exactly the same functions, I am not sure, or I don’t want to know clearly, whether a function is in a certain It is defined in "Package" (INCLUDE). Another problem is that we cannot include a package twice, but I don't want to spend too much time checking here. In the above example, executing test.php will generate many errors. . In C language, predefined functions are provided to solve this problem: #ifndef __fun1__
#define __fun1__
// do any thing
#endif PHP does not provide such a mechanism, but we can use PHP Flexibility to achieve the same function as the C language reservation, the following example is as follows:
// 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
// Other files may need to be included
require("test1.inc.php");
require("test2.inc.php");
// do any test
?> Now, we No longer afraid of errors that may occur if you include a package multiple times or define a function multiple times. The direct benefit this brings us is that it becomes easier to maintain our programs.

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian

How To Set Up Visual Studio Code (VS Code) for PHP Development
