w3pop.com :: ÍøÂçѧԺ :: PHP :: PHP º¯Êý
The real power of PHP comes from its functions.
PHPµÄÇ¿´ó¹¦ÄÜÖ÷ÒªÌåÏÖÔÚº¯ÊýÀï¡£
In PHP - there are more than 700 built-in functions available.
PHPÖй²°üº¬700¶à¸ö¿ÉÓõÄÄÚÖú¯Êý¡£
In this tutorial we will show you how to create your own functions.
ÔÚÕâ¸ö½Ì³ÌÖÐÎÒÃǽ«¸æËßÄãÈçºÎ´´½¨×Ô¼ºµÄº¯Êý
For a reference and examples of the built-in functions, please visit our PHP Reference.
Èç¹ûÄãÏëÁ˽â¸ü¶à¹ØÓÚPHP²ÎÊýºÍÄÚÖú¯ÊýµÄÀý×Ó£¬Çë·ÃÎÊPHP²ÎÊý¡£
A function is a block of code that can be executed whenever we need it.
º¯Êýʵ¼ÊÉÏÊÇÒ»¸öͳһµÄ´úÂë¿é£¬Äã¿ÉÒÔËæÊ±µ÷ÓÃËü¡£
Creating PHP functions:
´´½¨PHPº¯ÊýµÄ·½·¨£º
A simple function that writes my name when it is called:
ÏÂÃæÊÇÒ»¸ö¼òµ¥µÄPHPº¯Êý°¸Àý£¬µ±ÎÒÃǵ÷ÓÃËüʱ£¬Ëü¿ÉÒÔÊä³öÎÒÃǵÄÃû×Ö£º
<html> <?php writeMyName(); </body> |
Now we will use the function in a PHP script:
ÏÂÃæÎÒÃǽ«Ê¹ÓÃPHP½Å±¾³ÌÐòÊéдº¯Êý£º
<html> <?php echo "Hello world!<br />"; </body> |
The output of the code above will be:
ÉÏÊö´úÂ뽫»áÊä³öÏÂÃæµÄ½á¹û£º
Hello world! |
Our first function (writeMyName()) is a very simple function. It only writes a static string.
ÎÒÃǵĵÚÒ»¸öº¯Êý(writeOurName())ÊÇÒ»¸ö·Ç³£¼òµ¥µÄº¯Êý£¬ËüÖ»ÊÇÊéдÁËÒ»¶Î¾²Ì¬µÄ×Ö·û´®¡£
To add more functionality to a function, we can add parameters. A parameter is just like a variable.
Èç¹ûÄãÐèÒª¸øº¯Êý¼ÓÈë¸ü¶àµÄ¹¦ÄÜ£¬Äã¿ÉÒÔ¼ÌÐøÏòº¯ÊýÖÐÌí¼Ó²ÎÊý¡£²ÎÊý¾ÍÀàËÆÓÚÎÒÃÇ˵µÄ±äÁ¿¡£
You may have noticed the parentheses after the function name, like: writeMyName(). The parameters are specified inside the parentheses.
ÎÒÃÇÒѾעÒâµ½£¬º¯ÊýµÄÃû×ÖºóÃæ¶¼¼ÓÉÏÁËÒ»¸öÔ²À¨ºÅ“()”£»ÎÒÃÇÒªÌí¼ÓµÄ²ÎÊý¾ÍÊÇÔÚÔ²À¨ºÅ“()”ÄÚÖ¸¶¨µÄ¡£
The following example will write different first names, but the same last name:
ÏÂÃæµÄÀý×ÓÖУ¬Êä³öÃû×ֵIJ»Í¬£¬ÐÕÏàͬ£º
<html> <?php echo "My name is "; echo "My name is "; echo "My name is "; </body> |
The output of the code above will be:
ÉÏÊö´úÂëÊä³öµÄ½á¹û£º
My name is Kai Jim Refsnes. |
The following function has two parameters:
ÏÂÃæµÄº¯ÊýÖаüº¬Á½¸ö²ÎÊý£º
<html> <?php echo "My name is "; echo "My name is "; echo "My name is "; </body> |
The output of the code above will be:
ÉÏÊö´úÂëÊä³öµÄ½á¹û£º
My name is Kai Jim Refsnes. |
Functions can also be used to return values.
º¯ÊýÒ²¿ÉÒÔÓÃ×÷·µ»Ø“Öµ[value]”£º
<html> <?php echo "1 + 16 = " . add(1,16) </body> |
The output of the code above will be:
ÉÏÊö´úÂ뽫Êä³öÏÂÃæµÄ½á¹û£º
1 + 16 = 17 |