php 函数中定义函数

tech2023-12-05  33

php 函数中定义函数

Let’s start by defining the word “function.” A function is a self-contained piece of code which carries out a particular task (or function!). A key benefit of using functions is that they are reusable; if you have a task that needs to be performed a number of times, a function is an ideal solution. They can be either defined by you or by PHP (PHP has a rich collection of built-in functions). This article will focus on programmer-defined functions but will touch briefly on PHP’s functions to complete the picture.

让我们首先定义“功能”一词。 函数是执行特定任务(或函数!)的独立代码段。 使用函数的一个主要好处是它们是可重用的。 如果您的任务需要执行多次,则功能是理想的解决方案。 它们既可以由您定义,也可以由PHP定义(PHP具有丰富的内置函数集合)。 本文将重点讨论程序员定义的函数,但将简要介绍PHP的函数以完成说明。

定义功能 (Defining a Function)

So what does the syntax for defining a function look like? Here is a simple example:

那么定义函数的语法是什么样的呢? 这是一个简单的示例:

<?php function addNumbers($num1, $num2) { $result = $num1 + $num2; return $result; }

The keyword function lets PHP know that what follows is, you’ve guessed it, a function definition. Next, addNumbers is the name of the function. The open and close parentheses hold arguments (sometimes referred to as parameters), the values you’ll pass to the function when you invoke it. Functions do not have to accept arguments, in which case the parentheses would be empty. Here the variables $num1 and $num2 are arbitrary names and are referenced though within the function.

关键字function让PHP知道您已经猜到是函数定义。 接下来, addNumbers是函数的名称。 左括号和右括号包含参数(有时称为参数),即调用该函数时将传递给该函数的值。 函数不必接受参数,在这种情况下,括号将为空。 这里的变量$num1和$num2是任意名称,尽管在函数中被引用。

Note that the two statement lines within the function are contained within brackets. These lines make up what are known as the function’s body. The statements here are very simple: the first takes the values passed to the function as $num1 and $num2, adds them together and stores the resulting value in $result. The second line then uses return to pass the value of $result back to the calling statement.

请注意,函数中的两条语句行包含在方括号中。 这些线组成了功能的主体。 此处的语句非常简单:第一个语句将传递给函数的值作为$num1和$num2 ,将它们加在一起并将结果值存储在$result 。 然后,第二行使用return将$result的值传递回调用语句。

As with arguments, functions do not have to return values either. They might be used to carry out a calculation which is printed, for example. However, it is important to understand the concept of returning a value from a function since you will probably return values more often than not.

与参数一样,函数也不必返回值。 例如,它们可用于执行打印的计算。 但是,了解从函数返回值的概念很重要,因为您可能会经常返回值。

Functions will not be executed until you write some code to do so. To invoke the sample function, you would use a statement like this:

在编写一些代码之前,函数不会执行。 要调用示例函数,可以使用如下语句:

<?php $total = addNumbers($loanAmount, $interestAmount);

What does this mean? Well, the code after the = invokes or calls the function and causes its code to run. The values passed to the function are held in the two variables $loanAmount and $interestAmount. Notice that these names do not correspond with the argument names used when defining the function, i.e. $num1 and $num2. This doesn’t matter. The important point is that the function has been defined as having two arguments and you have supplied two arguments when executing the function. For obvious reasons, the values held in the variables $loanAmount and $interestAmount should be numeric since the function performs a mathematical operation.

这是什么意思? 好吧, =之后的代码将调用或调用该函数并导致其代码运行。 传递给函数的值保存在两个变量$loanAmount和$interestAmount 。 请注意,这些名称与定义函数时使用的参数名称不符,即$num1和$num2 。 没关系 重要的一点是,该函数已定义为具有两个参数,并且在执行该函数时已提供了两个参数。 由于明显的原因,变量$loanAmount和$interestAmount保存的值应该是数字,因为该函数执行数学运算。

Because return has been used in the function, the total held in $result will be passed back to the statement which executes the function. In this case the value will be assigned to $total.

因为在函数中使用了return,所以$result保存的总数将被传递回执行该函数的语句。 在这种情况下,该值将分配给$total 。

When naming a function, the name should be unique. It can be made up of letters, numbers, and the underscore, but must not start with a digit (the same rules for naming a variable). Thus, addNumbers and add_numbers are valid function names, while add numbers is not (embedded space) nor is 12add_numbers (starts with a digit). Naming your function abc123 is syntactically correct but unhelpful. Ideally, the function name should be meaningful too.

命名函数时,名称应唯一。 它可以由字母,数字和下划线组成,但不能以数字开头(命名变量的相同规则)。 因此, addNumbers和add_numbers是有效的函数名称,而add numbers并非(嵌入空格)也不是12add_numbers (以数字开头)。 命名函数abc123的语法正确,但无济于事。 理想情况下,函数名称也应该有意义。

As I mentioned at the start of this article, PHP defines some functions as well. It’s always worth looking to see if PHP has a function to do what you want before writing your own. But how do you know if you need to define your own function or if PHP provides one that does what you need? The answer is to familiarize yourself with the online documentation. For example, you might wish to format a date. Go first to www.php.net and in search box type “date”. You’ll be presented with information on the date() function and, on the left-hand side, a list of related date and time functions.

正如我在本文开头提到的那样,PHP还定义了一些函数。 始终值得一看的是,在编写自己PHP之前,PHP是否具有执行所需功能的功能。 但是,您如何知道是否需要定义自己的函数,或者PHP是否提供满足您需要的函数呢? 答案是使您熟悉在线文档。 例如,您可能希望格式化日期。 首先前往www.php.net,然后在搜索框中输入“日期”。 将为您提供有关date()函数的信息,以及在左侧的相关日期和时间函数的列表。

组织职能 (Organizing Functions)

Now that you’ve seen the syntax of a function, the next step is to decide where you should put the function code.

既然您已经了解了函数的语法,下一步就是确定应将函数代码放在何处。

Because functions are only executed on request, you could place them together at the beginning of your code. Here’s an example:

由于功能仅在请求时执行,因此您可以将它们放到代码的开头。 这是一个例子:

<?php function hello() { print "<h1>HELLO!</h1>"; print "<p>Welcome to my web site</p>"; } function printBreak($text) { print "$text<br>"; } function addNumbers($num1, $num2) { return $num1 + $num2; } hello(); printBreak("This is a line"); print addNumbers(3.75, 5.645);

This code displays the following output in a browser:

此代码在浏览器中显示以下输出:

The three functions are defined and then the code which executes them follows. Note that the function hello() does not have any arguments as its purpose is just to print a welcome message. The function printBreak() is a similar example – text is passed as an argument which is referenced in the function as the variable $text. Finally there is a slightly modified version of the addNumbers() function from earlier.

定义了三个函数,然后执行它们的代码。 请注意,函数hello()没有任何参数,因为它的目的只是打印欢迎消息。 函数printBreak()是一个类似的示例–文本作为参数传递,该参数在函数中被引用为变量$text 。 最后,还有一个稍稍修改过的addNumbers()函数版本。

At this point, the functions are only available in the script in which they have been defined. If you want to make them accessible to all of your scripts, it’s a better idea to place them in a separate file and include them. This approach means that any changes required to your functions later can be made only be made in one place, rather than having to amend multiple scripts.

此时,这些功能仅在定义它们的脚本中可用。 如果要使所有脚本都可以访问它们,最好将它们放在单独的文件中并包含它们。 这种方法意味着以后对功能的任何更改都只能在一个地方进行,而不必修改多个脚本。

Move the three functions into their own file named functions.php. Then, revise the example to use require. It should now look like this:

将这三个函数移到它们自己的名为functions.php的文件中。 然后,修改示例以使用require 。 现在看起来应该像这样:

<?php require "functions.php"; hello(); printBreak("This is a line"); print addNums(3.75, 5.645);

接受可变数量的参数 (Accepting a Variable Number of Arguments)

So far you’ve dealt only with functions which accept a fixed number of arguments. If you pass only one argument when two are required, you will see a warning message like this:

到目前为止,您只处理了接受固定数量参数的函数。 如果仅在需要两个参数时传递一个参数,则将显示以下警告消息:

Warning: Missing argument 2 for addNumbers() called in C:xampphtdocssitepointfunctions.php on line 17 and defined in C:xampphtdocssitepointfunctions.php on line 9

There may be circumstances when you want to pass a variable number of arguments – for example, you may need to calculate an average value from a range of numbers. In this case, the function would not define any arguments; instead, the number of values passed can be ascertained by using the PHP function func_num_args(). Another PHP function, func_get_arg(), allows you to retrieve the values passed into your function.

在某些情况下,您想要传递可变数量的参数–例如,您可能需要从一系列数字中计算平均值。 在这种情况下,该函数将不会定义任何参数。 相反,可以使用PHP函数func_num_args()确定传递的值的数量。 另一个PHP函数func_get_arg()允许您检索传递到函数中的值。

Here is an example which has been annotated with comments:

这是一个带有注释的示例:

<?php function calcAverage() { // initialize value to be used in calculation $total = 0; // find out how many arguments were given $arguments = func_num_args(); // loop to process each argument separately for ($i = 0; $i < $arguments; $i++) { // add the value in the current argument to the total $total += func_get_arg($i); } // after adding all arguments, calculate the average $average = $total / $arguments; // return the average return $average; } // invoke the function with 5 arguments echo calcAverage(44, 55, 66, 77, 88); // invoke the function with 8 arguments echo calcAverage(12, 34, 56, 78, 90, 9, 8, 7);

The function calcAverage() is executed twice, with a different numbers of arguments each time. Within calcAverage(), the function func_num_args() is called to determine the number of arguments that were passed in. The for loop, with which you may or may not be familiar with at this stage, retrieves each argument in turn using func_get_arg() and increments the total in $total. When all of the arguments have been retrieved and processed, the average value is calculated, returned, and printed using echo.

函数calcAverage()执行两次,每次参数数量不同。 在calcAverage() ,调用函数func_num_args()以确定传入的参数数量。在此阶段,您可能会或可能不熟悉的for循环使用func_get_arg()依次检索每个参数。并在$total中$total 。 检索并处理所有参数后,将使用echo来计算,返回平均值并打印平均值。

摘要 (Summary)

Let’s recap on some of the key concepts of functions:

让我们回顾一下函数的一些关键概念:

Easier maintenance – use functions so you don’t repeat code for common tasks.

易于维护 –使用功能,因此您无需为常见任务重复执行代码。

Reusability – functions can be used within individual scripts and across multiple scripts.

可重用性 –函数可以在单个脚本中使用,也可以在多个脚本中使用。

Flexibility – functions are flexible, accepting a specific number of arguments, or a variable number of arguments with func_num_args() and func_get_arg().

灵活性 –函数很灵活,可以接受特定数量的参数,或者使用func_num_args()和func_get_arg()接受可变数量的参数。

Improved Readability – separating functionality into functions streamlines your code and improves its readability.

改进的可读性 –将功能分成功能可以简化代码并提高其可读性。

You should now be equipped to create your own functions or find relevant ones from PHP’s extensive selection.

现在,您应该具备创建自己的功能或从PHP的广泛选择中找到相关功能的能力。

Image via kentoh / Shutterstock

图片来自kentoh / Shutterstock

翻译自: https://www.sitepoint.com/defining-and-using-functions-in-php/

php 函数中定义函数

相关资源:jdk-8u281-windows-x64.exe
最新回复(0)