Functions - PHP Manual Notes
User-defined functions
Function does not need to be defined before calling unless it is conditionally defined.
All functions and classes in PHP have global scope. PHP does not support function overloading, and it is not possible to undefine or redefine declared functions.
I tried it specifically. The maximum depth of the PHP recursion stack on my computer is 100.
Function parameters
PHP supports passing parameters by value (default), passing parameters by reference, and default parameters. Variable length parameter lists are also supported. PHP allows using arrays and special types NULL
as default parameters. If you want to allow a function to modify parameter values, you must pass parameters by reference.
Attention! When using default parameters, any default parameters must be placed to the right of any non-default parameters, otherwise the function will not work as expected.
PHP supports variable number of parameter lists in user-defined functions. In PHP 5.6 and above, there is ...
syntax implementation, which can be written like this, but it cannot be tested because there is no suitable environment.
<code><?php function sum(...$numbers) { $acc = 0; foreach($numbers as $n) { $acc += $n; } return $acc; } echo sum(1, 2, 3, 4);</code>
Of course, variable number of parameter lists can also be used in lower versions such as PHP 5.5. Obtain the number of parameters, the content of a certain parameter, and the parameter array through the functions func_num_args()
, func_get_arg()
, gunc_get_args()
.
<code><?php function sum() { $acc = 0; foreach(func_get_args() as $n) { $acc += $n; } return $acc; } echo sum(1, 2, 3, 4);</code>
Return value
Functions cannot return multiple values, but you can get a similar effect by returning an array.
<code><?php function small_numbers() { return array(0, 1, 2); } list($zero, $one, $two) = small_numbers(); echo "$zero $one $two";</code>
To return a reference from a function, you must use the reference operators &
both when declaring the function and when assigning the return value to a variable.
<code><?php function & return_reference() { return $someref; } $newref = & return_reference();</code>
Variable function
PHP supports variadic functions, that is, if there are parentheses after a variable name, PHP will look for a function with the same name as the variable's value and try to execute it. Variable functions can be used to implement callback functions, function tables, etc., although I have never used these.
When calling static methods, function calls take precedence over static properties.
Internal functions
PHP has many standard functions and structures, and some functions need to be compiled with specific PHP extension modules.
If the parameter type passed to the function is inconsistent with the actual type, the return value of the function is undefined. In this case, usually the function returns NULL
. But this is just a convention and doesn't have to be the case.
Anonymous function
Anonymous functions, also called closures, allow you to temporarily create a function without a specified name. The value most commonly used as a callback function argument.
The first example program in the manual is related to regular expressions, which I don’t know much about. The second example program is an anonymous function variable assignment. Note that a semicolon should be added at the end of the definition statement of the anonymous function variable.
<code><?php $greet = function($name) { echo "Hello $name "; }; $greet("world"); $greet(&#39;PHP&#39;);</code>
The third example program, about inheriting variables from the parent scope, I don’t understand, which is a pity. The fourth sample program, about Closures and scope, is combined with actual practice. It’s good, take a closer look.
This is a basic shopping cart class that implements the function of adding a certain number of products and calculating the total price. A closure is used as a callback function.
<code><?php class Cart { const PRICE_BUTTER = 1.00; const PRICE_MILK = 3.00; const PRICE_EGGS = 6.95; protected $products = array(); public function add($product, $quantity) { $this->products[$product] = $quantity; } public function getQuantity($product) { return isset($this->products[$product]) ? $this->products[$product] : FALSE; } public function getTotal($tax) { $total = 0.00; $callback = function($quantity, $product) use ($tax, &$total) { $pricePerItem = constant(__CLASS__ . "::PRICE_" . strtoupper($product)); $total += ($pricePerItem * $quantity) * ($tax + 1.0); }; array_walk($this->products, $callback); return round($total, 2); } } $mycart = new Cart; $mycart->add('butter', 1); $mycart->add('milk', 3); $mycart->add('eggs', 6); echo $mycart->getTotal(0.05);</code>
Attention! Be sure not to leave the semicolon at the end of the anonymous function statement!
(Full text ends)
The above introduces the functions - PHP manual notes, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
