当前位置:网站首页>PHP function
PHP function
2022-04-23 15:34:00 【Jimeng network worry free】
User defined functions
The parameters of the function
Return value
Variable function
Internal function
Anonymous functions
User defined functions
Definition
A function can be defined by the following syntax :
<?php
function foo($arg1, ..., $argn)
{
//do something
return $retval;
}
Naming specification
Function names and PHP The naming rules of other identifiers in are the same . Valid function names begin with letters or underscores , Followed by a letter , Number or underscore .
Functions do not need to be defined before calling
<?php
function actionA()
{
echo "A";
}
actionA();// You can call
actionB();// You can call
function actionB()
{
echo "B";
}
Unless the function is defined conditionally or function is invoked in the function. , Generally, it is not necessary to define before calling the function .
Calling function in function
<?php
function actionA()
{
function actionB()
{
echo "B";
}
}
actionB();// Unable to call
actionA();// Defined function actionB()
actionB();// You can call
PHP Function overloading is not supported , It is also impossible to undefine or redefine a declared function .
<?php
function sayHi()
{
echo 'Hi';
}
function sayHi()
{
echo 'Hello';
}
sayHi();// Report errors , Functions cannot be redefined sayHi()
Function names are case independent , But when you call a function , Usually use the same form as it was defined .
Recursive function
The essence of recursive function is to call the function itself , But avoid recursive functions / Method , Call over 100-200 layer , Because it may crash the stack and terminate the current script . Infinite recursion can be regarded as a programming error .
<?php
function recursion($a)
{
if ($a < 20) {
echo "$a\n";
recursion($a + 1);
}
}
The parameters of the function
You can pass information to functions through parameter lists , A list of expressions separated by commas .
PHP Support passing parameters by value ( Default ), Pass parameters and default parameters by reference . It also supports a variable number of parameters ;
Passing parameters by reference
By default , Function parameters are passed by values ( So even if you change the value of the parameter inside the function , It doesn't change the value outside the function ). If you want to allow a function to modify its parameter values , Parameters must be passed by reference . If you want a parameter of a function to always be passed by reference , You can prefix the parameter in the function definition with the symbol &:
<?php
function actionB(&$string)
{
$string .= 'and something extra.';
}
$str = 'This is a string, ';
actionB($str);
echo $str; // outputs 'This is a string, and something extra.'
?>
Default parameter value
Functions can be defined as C++ Default value of scalar parameter for style , as follows :
<?php
function makecoffee($type = "cappuccino")
{
return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?>
The above routine will output :
Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.
Return value
Value is returned by using an optional return statement . Can return any type including array and object . The return statement immediately aborts the function , And give control back to the line of code that called the function .
return
<?php
function square($num)
{
return $num * $num;
}
echo square(4); // outputs '16'.
Function cannot return more than one value , But you can get a similar effect by returning an array .
Return an array to get multiple return values
<?php
function small_numbers()
{
return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
Return a reference from a function , The reference operator must be used when a function declares and assigns a return value to a variable & :
Return a reference from a function
<?php
function &returns_reference()
{
return $someref;
}
$newref =& returns_reference();
?>
Return value type declaration
PHP 7 Added support for return type declaration . Similar to parameter type declaration , The return type declaration indicates the type of return value of the function . The available types are the same as those available in parameter declarations .
<?php
function arraysSum(array ...$arrays): array
{
return array_map(function(array $array): int {
return array_sum($array);
}, $arrays);
}
print_r(arraysSum([1,2,3], [4,5,6], [7,8,9]));
The above routine will output :
Array
(
[0] => 6
[1] => 15
[2] => 24
)
Variable function
PHP Support the concept of variable function . This means that if a variable name is followed by parentheses ,PHP Will look for a function with the same name as the value of the variable , And try to execute it . Variable functions can be used to implement, including callback functions , Some uses, including function tables .
Variable functions cannot be used in language structures , for example echo, print, unset(), isset(), empty(), include, require And similar statements . You need to use your own wrapper function to use these structures as variable functions .
edit /home/project/variable.php
<?php
class Test
{
public static $actionB = "property B";
public function actionA()
{
echo "method A";
}
public static function actionB()
{
echo "method B";
}
}
function sayHi() {
echo "Hi".PHP_EOL;
}
function sayHello($word = '') {
echo "Hello $word";
}
$func = 'sayHi';
$func();
$func = 'sayHello';
$func('World');
$func = 'actionA';
(new Test())->$func();
echo Test::$actionB;
$actionB = 'actionB';
Test::$actionB();
perform
php variable.php
It can be seen from the results
- You can use the syntax of variable functions to call an object method and static method .
- Static method calls take precedence over property calls
Internal function
Also known as built-in functions ,PHP There are many standard functions and structures . There are also functions that need to be and specific PHP Compile with the extension module , Otherwise, you will get a fatal undefined function error when using them .
for example , To use image Function imagecreatetruecolor(), Need to compile PHP When it's time to add GD Support for . perhaps , To use mysql_connect() function , You need to compile PHP When it's time to add MySQL Support .
call phpinfo() perhaps get_loaded_extensions() It can be learned that PHP Loaded those extension Libraries . At the same time, we should also pay attention to , Many extension libraries are valid by default .PHP Manuals organize their documentation according to different extension Libraries .
Note: If the parameter type passed to the function is inconsistent with the actual type , For example, a array Pass to a string Variable of type , Then the return value of the function is uncertain . under these circumstances , Usually the function returns NULL. But this is just a convention , Not necessarily .
See function_exists(), Function reference ,get_extension_funcs() and dl().
Anonymous functions
Anonymous functions (Anonymous functions), It's also called a closure function (closures), allow Temporarily create a function with no specified name . Most often used as a callback function (callback) The value of the parameter . Of course , There are other applications .
Anonymous functions are currently available through Closure Class to implement .
<?php
echo preg_replace_callback('~-([a-z])~', function ($match) {
return strtoupper($match[1]);
}, 'hello-world');
// Output helloWorld
Closure functions can also be used as values of variables .PHP This expression will be automatically converted into a built-in class Closure Object instance of . Put one closure Objects are assigned to a variable in the same way as ordinary variables , Finally, add a semicolon :
Anonymous function variable assignment
<?php
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
$greet('World');
$greet('PHP');
Inherit variables from parent scope
Closures can inherit variables from the parent scope . Any such variable should use the use The language structure passes in . PHP 7.1 rise , You cannot pass in such a variable : superglobals、 $this Or the same name as the parameter .
edit /home/project/anonymous.php
<?php
$msg = 'hello';
$a = function () {
var_dump($msg);
};
$a();
$b = function () use ($msg) {
var_dump($msg);
};
$b();
$msg = 'hi';
$b();
$c = function () use (&$msg) {
var_dump($msg);
};
$c();
$d = function ($arg) use ($msg) {
var_dump($arg . ' ' . $msg);
};
$d("hello");
perform
php anonymous.php
It can be seen from the results
Use use You can inherit variables from the parent scope
Anonymous functions inherit the parent scope variables when they are defined , Instead of inheriting at the time of invocation
Variables are assigned by reference , Then the original variable changes , The variable that references the variable will also change
版权声明
本文为[Jimeng network worry free]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231526352487.html
边栏推荐
- utils.DeprecatedIn35 因升级可能取消,该如何办
- Elk installation
- Advantages, disadvantages and selection of activation function
- Openstack theoretical knowledge
- JVM-第2章-类加载子系统(Class Loader Subsystem)
- 导入地址表分析(根据库文件名求出:导入函数数量、函数序号、函数名称)
- G007-HWY-CC-ESTOR-03 华为 Dorado V6 存储仿真器搭建
- 【递归之数的拆分】n分k,限定范围的拆分
- MySQL sync could not find first log file name in binary log index file error
- Basic concepts of website construction and management
猜你喜欢

Sorting and replying to questions related to transformer

让阿里P8都为之着迷的分布式核心原理解析到底讲了啥?看完我惊了

深度学习——超参数设置

2022年中国数字科技专题分析

G007-HWY-CC-ESTOR-03 华为 Dorado V6 存储仿真器搭建

Detailed explanation of kubernetes (XI) -- label and label selector

For examination

Demonstration meeting on startup and implementation scheme of swarm intelligence autonomous operation smart farm project

What if the server is poisoned? How does the server prevent virus intrusion?

Sword finger offer (1) -- for Huawei
随机推荐
MySQL Basics
移动app软件测试工具有哪些?第三方软件测评小编分享
控制结构(二)
Precautions for use of dispatching system
Collation of errors encountered in the use of redis shake
T2 icloud calendar cannot be synchronized
How did the computer reinstall the system? The display has no signal
Connect PHP to MySQL via PDO ODBC
Summary of interfaces for JDBC and servlet to write CRUD
MySQL query library size
Mysql database explanation (IX)
[backtrader source code analysis 18] Yahoo Py code comments and analysis (boring, interested in the code, you can refer to)
utils.DeprecatedIn35 因升级可能取消,该如何办
pgpool-II 4.3 中文手册 - 入门教程
重定向和请求转发详解
MultiTimer v2 重构版本 | 一款可无限扩展的软件定时器
API gateway / API gateway (III) - use of Kong - current limiting rate limiting (redis)
自主作业智慧农场创新论坛
WPS品牌再升级专注国内,另两款国产软件低调出国门,却遭禁令
Cookie&Session