自定义函数

1.函数的声明

代码示例:

<?php
function make_date_menus(){
    $month=array(1=>'January','February','March','April','May','June','July','August','September','October','November','Decemer');
    print '<select name="month">';
    foreach ($month as $key=>$value){
        print "
<option value="$key">$value</option>";
    }
    print '</select>';
}
make_date_menus();
?>

运行结果:

2.函数的参数

代码示例:

<?php
//函数创建粘性文本框
function make_text_input($name,$lable){
    print '<p><lable>'.$lable.':';
    print '<input type="text" name="'.$name.'"size = "20"';
    if(isset($_POST[$name])){
        print 'value="'.$_POST[$name].'"';
    }
    print '</lable>';
        
}
print '<form action="" method="post">';
make_text_input("name", "姓名");
make_text_input("email", "邮箱");
print '<input type="submit" name="submit" value="注册"/></form>'
?>

运行结果:

点击注册之后文本框并不清空,这就是粘性文本框

3.函数的返回值

代码示例:

function_return.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="function_return.php" method="post">
数量:<input type="text" name="quantity" size="5"><br>
单价:<input type="text" name="price" size="5"><br>
<input type="submit" name="submit" value="合计">
</form>
</body>
</html>

function_return.php

<?php
function cal_total($quantity,$price){
    $total = $quantity*$price;
    return $total;
}
if(is_numeric($_POST['quantity'])&&is_numeric($_POST['price'])){
    $total=cal_total($_POST['quantity'],$_POST['price']);
    print '<p>合计:'.$total.'</p>';
    
}else {
    print '请输入数字类型';
}
?>

运行结果:

 

 4.变量的作用范围

全局变量:

函数中若要使用全局变量时,在函数内必须使用global关键字定义目标变量,以告诉函数主体此变量为全局。

代码示例:

<?php
$one=200;
$two=100;
function demo(){
    global $one,$two;
    echo "结果:".($one+$two);
}
demo();
?>

5.参数传递

(1)传值(值传递)

默认是按值传递参数,函数内部改变了参数的值,不会改变函数体外部的值

代码示例:

<?php
function test($a){
    $a=200;
    echo "函数内部传输".$a;   //输出200
}
$var=100;
test($var);
echo "函数外部输出".$var;   //输出100
?>

(2)传址(引用传递)

函数定义时,在参数名的前面加上“&”,表示参数按引用传递,函数内部改变了参数的值,会改变函数体外部的值。

代码示例:

 (3)可变长参数列表

如果希望可以接受任意数量的参数时,定义函数时不带参数,在函数体内使用函数fun_get_args(),将传递的参数作为数组返回,同时还可以使用func_num_args()函数获得参数个数。

代码示例:

<?php
function more_arg(){
    $arg = func_get_args();
    for($i=0;$i<func_num_args();$i++){
        echo "参数是:".$arg[$i]."<br>";
    }
}
more_arg("one","two","three",1,2,3);
?>

运行结果:

(4)使用自定义的函数库

 

 

原文地址:https://www.cnblogs.com/sunxiaoyan/p/9261860.html