PHP 基础
PHP 简介
PHP 入门
PHP 语法
PHP 变量
PHP 常量
PHP 输出和打印
PHP 数据类型
PHP 字符串
PHP 运算符
PHP If…Else
PHP Switch…Case
PHP 数组
PHP 数组排序
PHP 循环
PHP 函数
PHP 数学运算
PHP GET 和 POST
PHP 高级
PHP 日期和时间
PHP 包含文件
PHP 文件系统
PHP 解析目录
PHP 文件上传
PHP 文件下载
PHP Cookies
PHP Sessions
PHP 发送邮件
PHP 表单处理
PHP 表单验证
PHP 过滤器
PHP 错误处理
PHP 类和对象
PHP 魔术常量
PHP JSON 解析
PHP 正则表达式
PHP 异常处理
PHP 和 MySQL 数据库
PHP MySQL 简介
PHP MySQL 连接
PHP MySQL Create Database
PHP MySQL Create Table
PHP MySQL Insert
PHP MySQL Prepared
PHP MySQL Last Inserted ID
PHP MySQL Select
PHP MySQL Where
PHP MySQL Limit
PHP MySQL Order By
PHP MySQL Update
PHP MySQL Delete
PHP MySQL CRUD 应用
PHP MySQL Ajax 搜索
PHP MySQL 登录系统
PHP参考
PHP String Functions
PHP Array Functions
PHP File System Functions
PHP Date/Time Functions
PHP Calendar Functions
PHP MySQLi Functions
PHP Filters
PHP Error Levels
PHP常见问题解答
如何在 PHP 中编写注释
如何在 PHP 中删除字符串中的空格
如何在 PHP 中查找字符串中的字符数
如何在 PHP 中查找字符串中的单词数
如何在 PHP 中删除字符串中的特殊字符
如何在 PHP 中替换字符串中的一个单词
如何在 PHP 中对字符串前面追加
如何在 PHP 中对字符串后面追加
如何在 PHP 中从字符串中提取子串
如何在 PHP 中比较两个字符串
如何在 PHP 中获取当前页面的 URL
如何在 PHP 中通过连接数组值创建字符串
如何在 PHP 中将字符串拆分为数组
如何在 PHP 中合并两个字符串
如何在 PHP 中把字符串转换成小写字母
如何在 PHP 中把字符串转换成大写字母
如何在 PHP 中把字符串的第一个字母转换成大写字母
如何在 PHP 中把特殊的 HTML 实体转换回字符
如何在 PHP 中删除字符串开头的空格
如何在 PHP 中删除字符串结尾的空格
如何在 PHP 中新建一行
如何在 PHP 中查找字符串长度
如何在 PHP 中检查变量是否已设置
如何在 PHP 中检查变量是否为空
如何在 PHP 中检查变量是否为NULL
如何在 PHP 中反转字符串
如何在 PHP 中用另一个字符串替换字符串的一部分
如何在 PHP 中计算子串在字符串中出现的次数
如何在 PHP 中计算数组中的所有元素
如何在 PHP 中打印或回显数组的所有值
如何在 PHP 中显示数组的结构和值
如何在 PHP 中颠倒数组的顺序
如何在 PHP 中检查数组中是否存在值
如何在 PHP 中检查数组中是否存在键
如何在 PHP 中删除数组中的最后一个元素
如何从 PHP 数组中删除第一个元素
如何在 PHP 中为数组的开头添加元素
如何在 PHP 中为数组的末尾添加元素
如何在 PHP 中把两个或多个数组合并成一个数组
如何在 PHP 中按字母顺序对数组值排序
如何在 PHP 中删除数组中的重复值
如何在 PHP 中随机调整数组的顺序
如何在 PHP 中比较两个数组的值
如何在 PHP 中计算数组中数值的总和
如何在 PHP 中删除数组中的空值
如何在 PHP 中用数组值填充下拉列表
如何在 PHP 中获取关联数组的所有键值
如何在 PHP 中获取关联数组的所有值
如何在 PHP 中按键对关联数组排序
如何在 PHP 中按值对关联数组排序
如何在 PHP 中从数组中获取单个值
如何在 PHP 中循环浏览多维数组
如何在 PHP 中从数组中删除元素
如何在 PHP 中检查字符串是否包含特定单词
如何在 PHP 中获取当前日期和时间
如何在 PHP 中进行重定向
如何在 PHP 中删除字符串中的所有空格
如何用 PHP 获取当前年份
如何在 PHP 中将日期从 yyyy-mm-dd 转换为 dd-mm-yyyy 格式
如何在 PHP 中将字符串转换为数字
如何在 PHP 中获取数组的第一个元素
如何在 PHP 中将日期转换为时间戳
如何在 PHP 中为空数组添加元素
如何在 PHP 中把整数转换成字符串
如何用值而不是键删除 PHP 数组元素
如何在 PHP 中将键和值同时推入数组
如何使用 PHP 定期刷新页面
如何从 PHP 字符串中删除最后一个字符
如何从 PHP 脚本返回 JSON
如何让 PHP 显示错误
PHP 函数 - php7基础教程 - 笔下光年
网站首页
PHP 函数
In this tutorial you will learn how to create your own custom functions in PHP. ## PHP Built-in Functions A function is a self-contained block of code that performs a specific task. PHP has a huge collection of internal or built-in functions that you can call directly within your PHP scripts to perform a specific task, like `gettype()`, `print_r()`, `var_dump`, etc. Please check out PHP reference section for a complete list of useful PHP built-in functions. ## PHP User-Defined Functions In addition to the built-in functions, PHP also allows you to define your own functions. It is a way to create reusable code packages that perform specific tasks and can be kept and maintained separately form main program. Here are some advantages of using functions: - Functions reduces the repetition of code within a program — Function allows you to extract commonly used block of code into a single component. Now you can perform the same task by calling this function wherever you want within your script without having to copy and paste the same block of code again and again. - Functions makes the code much easier to maintain — Since a function created once can be used many times, so any changes made inside a function automatically implemented at all the places without touching the several files. - Functions makes it easier to eliminate the errors — When the program is subdivided into functions, if any error occur you know exactly what function causing the error and where to find it. Therefore, fixing errors becomes much easier. - Functions can be reused in other application — Because a function is separated from the rest of the script, it's easy to reuse the same function in other applications just by including the php file containing those functions. The following section will show you how easily you can define your own function in PHP. ## Creating and Invoking Functions The basic syntax of creating a custom function can be give with: ```php function functionName(){ // Code to be executed } ``` The declaration of a user-defined function start with the word function, followed by the name of the function you want to create followed by parentheses i.e. () and finally place your function's code between curly brackets {}. This is a simple example of an user-defined function, that display today's date: ```php <?php // Defining function function whatIsToday(){ echo "Today is " . date('l', mktime()); } // Calling function whatIsToday(); ?> ``` <div class="callout callout-info mb-3">Note: A function name must start with a letter or underscore character not with a number, optionally followed by the more letters, numbers, or underscore characters. Function names are case-insensitive.</div> ## Functions with Parameters You can specify parameters when you define your function to accept input values at run time. The parameters work like placeholder variables within a function; they're replaced at run time by the values (known as argument) provided to the function at the time of invocation. ```php function myFunc($oneParameter, $anotherParameter){ // Code to be executed } ``` You can define as many parameters as you like. However for each parameter you specify, a corresponding argument needs to be passed to the function when it is called. The `getSum()` function in following example takes two integer values as arguments, simply add them together and then display the result in the browser. ```php <?php // Defining function function getSum($num1, $num2){ $sum = $num1 + $num2; echo "Sum of the two numbers $num1 and $num2 is : $sum"; } // Calling function getSum(10, 20); ?> ``` The output of the above code will be: ``` Sum of the two numbers 10 and 20 is : 30 ``` <div class="callout callout-success mb-3">Tip: An argument is a value that you pass to a function, and a parameter is the variable within the function that receives the argument. However, in common usage these terms are interchangeable i.e. an argument is a parameter is an argument.</div> ## Functions with Optional Parameters and Default Values You can also create functions with optional parameters — just insert the parameter name, followed by an equals (`=`) sign, followed by a default value, like this. ```php <?php // Defining function function customFont($font, $size=1.5){ echo "<p style=\"font-family: $font; font-size: {$size}em;\">Hello, world!</p>"; } // Calling function customFont("Arial", 2); customFont("Times", 3); customFont("Courier"); ?> ``` As you can see the third call to `customFont()` doesn't include the second argument. This causes PHP engine to use the default value for the `$size` parameter which is 1.5. ## Returning Values from a Function A function can return a value back to the script that called the function using the return statement. The value may be of any type, including arrays and objects. ```php <?php // Defining function function getSum($num1, $num2){ $total = $num1 + $num2; return $total; } // Printing returned value echo getSum(5, 10); // Outputs: 15 ?> ``` A function can not return multiple values. However, you can obtain similar results by returning an array, as demonstrated in the following example. ```php <?php // Defining function function divideNumbers($dividend, $divisor){ $quotient = $dividend / $divisor; $array = array($dividend, $divisor, $quotient); return $array; } // Assign variables as if they were an array list($dividend, $divisor, $quotient) = divideNumbers(10, 2); echo $dividend; // Outputs: 10 echo $divisor; // Outputs: 2 echo $quotient; // Outputs: 5 ?> ``` ## Passing Arguments to a Function by Reference In PHP there are two ways you can pass arguments to a function: by value and by reference. By default, function arguments are passed by value so that if the value of the argument within the function is changed, it does not get affected outside of the function. However, to allow a function to modify its arguments, they must be passed by reference. Passing an argument by reference is done by prepending an ampersand (`&`) to the argument name in the function definition, as shown in the example below: ```php <?php /* Defining a function that multiply a number by itself and return the new value */ function selfMultiply(&$number){ $number *= $number; return $number; } $mynum = 5; echo $mynum; // Outputs: 5 selfMultiply($mynum); echo $mynum; // Outputs: 25 ?> ``` ## Understanding the Variable Scope However, you can declare the variables anywhere in a PHP script. But, the location of the declaration determines the extent of a variable's visibility within the PHP program i.e. where the variable can be used or accessed. This accessibility is known as variable scope. By default, variables declared within a function are local and they cannot be viewed or manipulated from outside of that function, as demonstrated in the example below: ```php <?php // Defining function function test(){ $greet = "Hello World!"; echo $greet; } test(); // Outputs: Hello World! echo $greet; // Generate undefined variable error ?> ``` Similarly, if you try to access or import an outside variable inside the function, you'll get an undefined variable error, as shown in the following example: ```php <?php $greet = "Hello World!"; // Defining function function test(){ echo $greet; } test(); // Generate undefined variable error echo $greet; // Outputs: Hello World! ?> ``` As you can see in the above examples the variable declared inside the function is not accessible from outside, likewise the variable declared outside of the function is not accessible inside of the function. This separation reduces the chances of variables within a function getting affected by the variables in the main program. <div class="callout callout-success mb-3">Tip: It is possible to reuse the same name for a variable in different functions, since local variables are only recognized by the function in which they are declared.</div> ## The global Keyword There may be a situation when you need to import a variable from the main program into a function, or vice versa. In such cases, you can use the `global` keyword before the variables inside a function. This keyword turns the variable into a global variable, making it visible or accessible both inside and outside the function, as show in the example below: ```php <?php $greet = "Hello World!"; // Defining function function test(){ global $greet; echo $greet; } test(); // Outpus: Hello World! echo $greet; // Outpus: Hello World! // Assign a new value to variable $greet = "Goodbye"; test(); // Outputs: Goodbye echo $greet; // Outputs: Goodbye ?> ``` You will learn more about visibility and access control in [PHP classes and objects](http://www.bixiaguangnian.com/manual/php7/3994.html "PHP classes and objects") chapter. ## Creating Recursive Functions A recursive function is a function that calls itself again and again until a condition is satisfied. Recursive functions are often used to solve complex mathematical calculations, or to process deeply nested structures e.g., printing all the elements of a deeply nested array. The following example demonstrates how a recursive function works. ```php <?php // Defining recursive function function printValues($arr) { global $count; global $items; // Check input is an array if(!is_array($arr)){ die("ERROR: Input is not an array"); } /* Loop through array, if value is itself an array recursively call the function else add the value found to the output items array, and increment counter by 1 for each value found */ foreach($arr as $a){ if(is_array($a)){ printValues($a); } else{ $items[] = $a; $count++; } } // Return total count and values found in array return array('total' => $count, 'values' => $items); } // Define nested array $species = array( "birds" => array( "Eagle", "Parrot", "Swan" ), "mammals" => array( "Human", "cat" => array( "Lion", "Tiger", "Jaguar" ), "Elephant", "Monkey" ), "reptiles" => array( "snake" => array( "Cobra" => array( "King Cobra", "Egyptian cobra" ), "Viper", "Anaconda" ), "Crocodile", "Dinosaur" => array( "T-rex", "Alamosaurus" ) ) ); // Count and print values in nested array $result = printValues($species); echo $result['total'] . ' value(s) found: '; echo implode(', ', $result['values']); ?> ``` <div class="callout callout-info mb-3">Note: Be careful while creating recursive functions, because if code is written improperly it may result in an infinite loop of function calling.</div>
上一篇:
PHP 循环
下一篇:
PHP 数学运算