当前位置:网站首页>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
边栏推荐
- MySQL InnoDB transaction
- Openstack command operation
- 深度学习——超参数设置
- setcontext getcontext makecontext swapcontext
- 软件性能测试报告起着什么作用?第三方测试报告如何收费?
- 木木一路走好呀
- Pytorch中named_parameters、named_children、named_modules函数
- Node.js ODBC连接PostgreSQL
- Common types of automated testing framework ▏ automated testing is handed over to software evaluation institutions
- 函数(第一部分)
猜你喜欢
G007-hwy-cc-estor-03 Huawei Dorado V6 storage simulator construction
Detailed explanation of MySQL connection query
Openstack command operation
Differential privacy (background)
深度学习——超参数设置
X509 certificate cer format to PEM format
Mysql database explanation (VII)
cadence SPB17.4 - Active Class and Subclass
自主作业智慧农场创新论坛
setcontext getcontext makecontext swapcontext
随机推荐
Nacos程序连接MySQL8.0+ NullPointerException
Use of common pod controller of kubernetes
Mysql database explanation (10)
How did the computer reinstall the system? The display has no signal
php函数
What exactly does the distributed core principle analysis that fascinates Alibaba P8? I was surprised after reading it
自主作业智慧农场创新论坛
Today's sleep quality record 76 points
Pytorch中named_parameters、named_children、named_modules函数
Node. JS ODBC connection PostgreSQL
Advantages, disadvantages and selection of activation function
C language super complete learning route (collection allows you to avoid detours)
Functions (Part I)
Summary of interfaces for JDBC and servlet to write CRUD
服务器中毒了怎么办?服务器怎么防止病毒入侵?
T2 iCloud日历无法同步
regular expression
Code live collection ▏ software test report template Fan Wen is here
Machine learning - logistic regression
小程序知识点积累