技术开发 频道

PHP开发经典教程(Part 6):编写自定义函数

“周一早上忧虑症候群” 

    为了弄明白函数是如何工作的,请看下面的例子:

<?php // define a function function myStandardResponse() { echo "Get lost, jerk!<br /><br />"; } // on the bus echo "Hey lady, can you spare a dime? <br />"; myStandardResponse(); // at the office echo "Can you handle Joe's workload,
in addition to your own,
while he's in Tahiti for a month?
You'll probably need to come in early and work till midnight,
but we are confident you can handle it.
Oh, and we can't pay you extra because of budgetary constraints...<br />"; myStandardResponse(); // at the party echo "Hi, haven't I seen you somewhere before?<br />"; myStandardResponse();
?>


    输出结果如同下面所示:

Hey lady, can you spare a dime?
Get lost, jerk!

Can you handle Joe's workload, in addition to your own, while he's in Tahiti for a month?
You'll probably need to come in early and work till midnight, but we are confident you can
handle it. Oh, and we can't pay you extra because of budgetary constraints...
Get lost, jerk!

Hi, haven't I seen you somewhere before?
Get lost, jerk!

    很显然,这段代码未经加工,但它确实展示了函数是如何允许你重用代码段的。 

    在上述脚本中我所做的第一件事情就是定义一个带有函数关键字的新函数。在该关键字后跟着函数的名称,在这个例子中就是myStandardResponse()函数。附着至该函数的所有编程代码接着置放在一对大括号内—且该程序代码可含有循环结构、条件语句、调用其他用户定义的函数或者其他PHP函数。 

    当然,定义函数只是问题的一半。如果你想让函数在任何情况下起作用,你需要对其进行“调用”。在PHP中,就像在一百万个其他语言中一样,函数调用是通过函数名称来调用函数而完成的,就像我在上述例子中所做的那样。调用用户定义的函数和调用PHP内置的函数(比如echo()或者explode())的方法是一致的。 

    下面是函数的典型格式:

function function_name (optional function arguments) {
statement 1...
statement 2...
.
.
.
statement n...
}

 

0
相关文章