创建PHP函数
语法:
<?php function functionName() { // 要执行的代码 } ?>
PHP 函数准则:
- 函数的名称应该提示出它的功能
- 函数名称以字母或下划线开头(不能以数字开头)
实例:
<?php function writeName() { echo "Kai Jim Refsnes"; } echo "My name is "; writeName(); ?>
输出:My name is Kai Jim Refsnes
PHP函数 - 添加参数
为了给函数添加更多的功能,我们可以添加参数。参数类似变量。
参数就在函数名称后面有一个括号内指定。
实例1:
<?php function writeName($fname) { echo $fname . " Refsnes.<br>"; } echo "My name is "; writeName("Kai Jim"); echo "My sister's name is "; writeName("Hege"); echo "My brother's name is "; writeName("Stale"); ?>
输出:
My name is Kai Jim Refsnes. My sister's name is Hege Refsnes. My brother's name is Stale Refsnes.
实例2
下面的函数有两个参数:
<?php function writeName($fname,$punctuation) { echo $fname . " Refsnes" . $punctuation . "<br>"; } echo "My name is "; writeName("Kai Jim","."); echo "My sister's name is "; writeName("Hege","!"); echo "My brother's name is "; writeName("Ståle","?"); ?>
输出:
My name is Kai Jim Refsnes. My sister's name is Hege Refsnes! My brother's name is Ståle Refsnes?
PHP 函数 - 返回值
如果函数返回一个值,请使用return
<?php function add($x,$y) { $total=$x+$y; return $total; } echo "1 + 16 = " . add(1,16); ?>
输出:1 + 16 = 17