= PHP_4_0_4, PHP_5, PHP_7, PHP_8 // call_user_func() - PHP_4, PHP_5, PHP_7, PHP_8 // OFFLINE | forward_static_call_array() - PHP_5 >= PHP_5_3_0, PHP_7, PHP_8 // OFFLINE | forward_static_call() - PHP_5 >= PHP_5_3_0, PHP_7, PHP_8 // func_get_arg() - PHP_4, PHP_5, PHP_7, PHP_8 // func_get_args() - PHP_4, PHP_5, PHP_7, PHP_8 // func_num_args() - PHP_4, PHP_5, PHP_7, PHP_8 // function_exists() - PHP_4, PHP_5, PHP_7, PHP_8 // get_defined_functions() - PHP_4 >= PHP_4_0_4, PHP_5, PHP_7, PHP_8 // register_shutdown_function() - PHP_4, PHP_5, PHP_7, PHP_8 // register_tick_function() - PHP_4 >= PHP_4_0_3, PHP_5, PHP_7, PHP_8 // unregister_tick_function() - PHP_4 >= PHP_4_0_3, PHP_5, PHP_7, PHP_8 // OFFLINE | create_function() - PHP_4 >= PHP_4_0_1, PHP_5, PHP_7 // ============================== USING CLASSES (0) // ============================== USING DATA_TYPES (7) // mixed // callable // array // int // bool // string // void // ============================== END // REQUIREMENTS // ============================== // ============================== BEGIN // PHP_VARIABLE_FUNCTIONHANDLING // ============================== ABOUT // PHP Manual / Function Reference / Variable and Type Related Extensions / Function Handling // URL: https://www.php.net/manual/en/book.funchand.php // ============================== DESCRIPTION // FUNCTION_HANDLING // LANGUAGE_REFERENCE_FUNCTIONS // // FUNCTION_HANDLING - BEGIN // Function Handling // // INTRODUCTION // INSTALLING_CONFIGURING // PREDEFINED_CONSTANTS // FUNCTION_HANDLING_FUNCTIONS // // INTRODUCTION - BEGIN // Introduction // // These functions all handle various operations involved in working with functions. // // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-22) // URL: https://www.php.net/manual/en/intro.funchand.php // INTRODUCTION - END // // INSTALLING_CONFIGURING - BEGIN // Installing/Configuring // // REQUIREMENTS // INSTALLATION // RUNTIME_CONFIGURATION // RESOURCE_TYPES // // REQUIREMENTS - BEGIN // Requirements // // No external libraries are needed to build this extension. // // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-22) // URL: https://www.php.net/manual/en/funchand.requirements.php // REQUIREMENTS - END // // INSTALLATION - BEGIN // Installation // // There is no installation needed to use these functions; they are part of the PHP core. // // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-22) // URL: https://www.php.net/manual/en/funchand.installation.php // INSTALLATION - END // // RUNTIME_CONFIGURATION - BEGIN // Runtime Configuration // // This extension has no configuration directives defined in php.ini. // // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-22) // URL: https://www.php.net/manual/en/funchand.configuration.php // RUNTIME_CONFIGURATION - END // // RESOURCE_TYPES - BEGIN // Resource Types // // This extension has no resource types defined. // // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-22) // URL: https://www.php.net/manual/en/funchand.resources.php // RESOURCE_TYPES - END // // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-22) // URL: https://www.php.net/manual/en/funchand.setup.php // INSTALLING_CONFIGURING - END // // PREDEFINED_CONSTANTS - BEGIN // Predefined Constants // // This extension has no constants defined. // // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-22) // URL: https://www.php.net/manual/en/funchand.constants.php // PREDEFINED_CONSTANTS - END // // FUNCTION_HANDLING_FUNCTIONS - BEGIN // Function handling Functions // // Table of Contents // * call_user_func_array - Call a callback with an array of parameters // * call_user_func - Call the callback given by the first parameter // * create_function - Create a function dynamically by evaluating a string of code // * forward_static_call_array - Call a static method and pass the arguments as array // * forward_static_call - Call a static method // * func_get_arg - Return an item from the argument list // * func_get_args - Returns an array comprising a function's argument list // * func_num_args - Returns the number of arguments passed to the function // * function_exists - Return true if the given function has been defined // * get_defined_functions - Returns an array of all defined functions // * register_shutdown_function - Register a function for execution on shutdown // * register_tick_function - Register a function for execution on each tick // * unregister_tick_function - De-register a function for execution on each tick // // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-22) // URL: https://www.php.net/manual/en/ref.funchand.php // FUNCTION_HANDLING_FUNCTIONS - END // // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-22) // URL: https://www.php.net/manual/en/book.funchand.php // FUNCTION_HANDLING - END // // LANGUAGE_REFERENCE_FUNCTIONS - BEGIN // Functions (PHP Manual / Language Reference / Functions) // // USER_DEFINED_FUNCTIONS // FUNCTION_ARGUMENTS // RETURNING_VALUES // VARIABLE_FUNCTIONS // INTERNAL_BUILT_IN_FUNCTIONS // ANONYMOUS_FUNCTIONS // ARROW_FUNCTIONS // FIRST_CLASS_CALLABLE_SYNTAX // // USER_DEFINED_FUNCTIONS - BEGIN // User-defined functions // // [example] // A function may be defined using syntax such as the following: // Example #1 Pseudo code to demonstrate function uses // [php] // function foo($arg_1, $arg_2, /* ..., */ $arg_n) // { // echo "Example function.\n"; // return $retval; // } // [/php] // Any valid PHP code may appear inside a function, even other functions and class definitions. // Function names follow the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$. // Tip: See also the Userland Naming Guide. // Functions need not be defined before they are referenced, except when a function is conditionally defined as shown in the two examples below. // When a function is defined in a conditional manner such as the two examples shown. Its definition must be processed prior to being called. // [/example] // [example] // Example #2 Conditional functions // [php] // // $makefoo = true; // // /* We can't call foo() from here // since it doesn't exist yet, // but we can call bar() */ // // bar(); // // if ($makefoo) { // function foo() // { // echo "I don't exist until program execution reaches me.\n"; // } // } // // /* Now we can safely call foo() // since $makefoo evaluated to true */ // // if ($makefoo) foo(); // // function bar() // { // echo "I exist immediately upon program start.\n"; // } // // [/php] // [/example] // [example] // Example #3 Functions within functions // [php] // function foo() // { // function bar() // { // echo "I don't exist until foo() is called.\n"; // } // } // // /* We can't call bar() yet // since it doesn't exist. */ // // foo(); // // /* Now we can call bar(), // foo()'s processing has // made it accessible. */ // // bar(); // // [/php] // All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa. // PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions. // Note: Function names are case-insensitive for the ASCII characters A to Z, though it is usually good form to call functions as they appear in their declaration. // Both variable number of arguments and default arguments are supported in functions. See also the function references for func_num_args(), func_get_arg(), and func_get_args() for more information. // It is possible to call recursive functions in PHP. // [/example] // [example] // Example #4 Recursive functions // [php] // function recursion($a) // { // if ($a < 20) { // echo "$a\n"; // recursion($a + 1); // } // } // [/php] // Note: Recursive function/method calls with over 100-200 recursion levels can smash the stack and cause a termination of the current script. Especially, infinite recursion is considered a programming error. // [/example] // // ===== LITERATURE_SOURCES // * PHP_NET (2023-11-11) // URL: https://www.php.net/manual/en/functions.user-defined.php // USER_DEFINED_FUNCTIONS - END // // FUNCTION_ARGUMENTS - BEGIN // Function arguments // // Information may be passed to functions via the argument list, which is a comma-delimited list of expressions. The arguments are evaluated from left to right, before the function is actually called (eager evaluation). // PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists and Named Arguments are also supported. // [example] // Example #1 Passing arrays to functions // [php] // function takes_array($input) // { // echo "$input[0] + $input[1] = ", $input[0]+$input[1]; // } // [/php] // [/example] // As of PHP 8.0.0, the list of function arguments may include a trailing comma, which will be ignored. That is particularly useful in cases where the list of arguments is long or contains long variable names, making it convenient to list arguments vertically. // [example] // Example #2 Function Argument List with trailing Comma // [php] // function takes_many_args( // $first_arg, // $second_arg, // $a_very_long_argument_name, // $arg_with_default = 5, // $again = 'a default string', // This trailing comma was not permitted before 8.0.0. // ) // { // // ... // } // [/php] // [/example] // // Passing arguments 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 changed outside of the function). To allow a function to modify its arguments, they must be passed by reference. // To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition: // [example] // Example #3 Passing function parameters by reference // [php] // function add_some_extra(&$string) // { // $string .= 'and something extra.'; // } // $str = 'This is a string, '; // add_some_extra($str); // echo $str; // outputs 'This is a string, and something extra.' // [/php] // [/example] // It is an error to pass a value as argument which is supposed to be passed by reference. // // Default argument values // A function may define default values for arguments using syntax similar to assigning a variable. The default is used only when the parameter is not specified; in particular, note that passing null does not assign the default value. // [example] // Example #4 Use of default parameters in functions // [php] // function makecoffee($type = "cappuccino") // { // return "Making a cup of $type.\n"; // } // echo makecoffee(); // echo makecoffee(null); // echo makecoffee("espresso"); // [/php] // The above example will output: // [result] // Making a cup of cappuccino. // Making a cup of . // Making a cup of espresso. // [/result] // [/example] // Default parameter values may be scalar values, arrays, the special type null, and as of PHP 8.1.0, objects using the new ClassName() syntax. // [example] // Example #5 Using non-scalar types as default values // [php] // function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL) // { // $device = is_null($coffeeMaker) ? "hands" : $coffeeMaker; // return "Making a cup of ".join(", ", $types)." with $device.\n"; // } // echo makecoffee(); // echo makecoffee(array("cappuccino", "lavazza"), "teapot"); // [/php] // [/example] // [example] // Example #6 Using objects as default values (as of PHP 8.1.0) // [php] // class DefaultCoffeeMaker { // public function brew() { // return 'Making coffee.'; // } // } // class FancyCoffeeMaker { // public function brew() { // return 'Crafting a beautiful coffee just for you.'; // } // } // function makecoffee($coffeeMaker = new DefaultCoffeeMaker) // { // return $coffeeMaker->brew(); // } // echo makecoffee(); // echo makecoffee(new FancyCoffeeMaker); // [/php] // [/example] // The default value must be a constant expression, not (for example) a variable, a class member or a function call. // Note that any optional arguments should be specified after any required arguments, otherwise they cannot be omitted from calls. Consider the following example: // [example] // Example #7 Incorrect usage of default function arguments // [php] // function makeyogurt($container = "bowl", $flavour) // { // return "Making a $container of $flavour yogurt.\n"; // } // // echo makeyogurt("raspberry"); // "raspberry" is $container, not $flavour // [/php] // The above example will output: // [result] // Fatal error: Uncaught ArgumentCountError: Too few arguments // to function makeyogurt(), 1 passed in example.php on line 42 // [/result] // [/example] // Now, compare the above with this: // [example] // Example #8 Correct usage of default function arguments // [php] // function makeyogurt($flavour, $container = "bowl") // { // return "Making a $container of $flavour yogurt.\n"; // } // // echo makeyogurt("raspberry"); // "raspberry" is $flavour // [/php] // The above example will output: // [result] // Making a bowl of raspberry yogurt. // [/result] // [/example] // As of PHP 8.0.0, named arguments can be used to skip over multiple optional parameters. // [example] // Example #9 Correct usage of default function arguments // [php] // function makeyogurt($container = "bowl", $flavour = "raspberry", $style = "Greek") // { // return "Making a $container of $flavour $style yogurt.\n"; // } // // echo makeyogurt(style: "natural"); // [/php] // The above example will output: // [result] // Making a bowl of raspberry natural yogurt. // [/result] // [/example] // As of PHP 8.0.0, declaring mandatory arguments after optional arguments is deprecated. This can generally be resolved by dropping the default value, since it will never be used. One exception to this rule are arguments of the form Type $param = null, where the null default makes the type implicitly nullable. This usage remains allowed, though it is recommended to use an explicit nullable type instead. // [example] // Example #10 Declaring optional arguments after mandatory arguments // [php] // function foo($a = [], $b) {} // Default not used; deprecated as of PHP 8.0.0 // function foo($a, $b) {} // Functionally equivalent, no deprecation notice // // function bar(A $a = null, $b) {} // Still allowed; $a is required but nullable // function bar(?A $a, $b) {} // Recommended // [/php] // [/example] // Note: As of PHP 7.1.0, omitting a parameter which does not specify a default throws an ArgumentCountError; in previous versions it raised a Warning. // Note: Arguments that are passed by reference may have a default value. // // Variable-length argument lists // PHP has support for variable-length argument lists in user-defined functions by using the ... token. // Argument lists may include the ... token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array: // [example] // Example #11 Using ... to access variable arguments // [php] // function sum(...$numbers) { // $acc = 0; // foreach ($numbers as $n) { // $acc += $n; // } // return $acc; // } // // echo sum(1, 2, 3, 4); // [/php] // The above example will output: // [result] // 10 // [/result] // [/example] // ... can also be used when calling functions to unpack an array or Traversable variable or literal into the argument list: // [example] // Example #12 Using ... to provide arguments // [php] // function add($a, $b) { // return $a + $b; // } // // echo add(...[1, 2])."\n"; // // $a = [1, 2]; // echo add(...$a); // [/php] // The above example will output: // [result] // 3 // 3 // [/result] // [/example] // You may specify normal positional arguments before the ... token. In this case, only the trailing arguments that don't match a positional argument will be added to the array generated by .... // It is also possible to add a type declaration before the ... token. If this is present, then all arguments captured by ... must match that parameter type. // [example] // Example #13 Type declared variable arguments // [php] // function total_intervals($unit, DateInterval ...$intervals) { // $time = 0; // foreach ($intervals as $interval) { // $time += $interval->$unit; // } // return $time; // } // // $a = new DateInterval('P1D'); // $b = new DateInterval('P2D'); // echo total_intervals('d', $a, $b).' days'; // // // This will fail, since null isn't a DateInterval object. // echo total_intervals('d', null); // [/php] // The above example will output: // [result] // 3 days // Catchable fatal error: Argument 2 passed to total_intervals() must be an instance of DateInterval, null given, called in - on line 14 and defined in - on line 2 // [/result] // [/example] // Finally, variable arguments can also be passed by reference by prefixing the ... with an ampersand (&). // // Named Arguments // PHP 8.0.0 introduced named arguments as an extension of the existing positional parameters. Named arguments allow passing arguments to a function based on the parameter name, rather than the parameter position. This makes the meaning of the argument self-documenting, makes the arguments order-independent and allows skipping default values arbitrarily. // Named arguments are passed by prefixing the value with the parameter name followed by a colon. Using reserved keywords as parameter names is allowed. The parameter name must be an identifier, specifying dynamically is not allowed. // [example] // Example #14 Named argument syntax // [php] // myFunction(paramName: $value); // array_foobar(array: $value); // // // NOT supported. // function_name($variableStoringParamName: $value); // [/php] // [/example] // [example] // Example #15 Positional arguments versus named arguments // [php] // // Using positional arguments: // array_fill(0, 100, 50); // // // Using named arguments: // array_fill(start_index: 0, count: 100, value: 50); // [/php] // [/example] // The order in which the named arguments are passed does not matter. // [example] // Example #16 Same example as above with a different order of parameters // [php] // array_fill(value: 50, count: 100, start_index: 0); // [/php] // [/example] // Named arguments can be combined with positional arguments. In this case, the named arguments must come after the positional arguments. It is also possible to specify only some of the optional arguments of a function, regardless of their order. // [example] // Example #17 Combining named arguments with positional arguments // [php] // htmlspecialchars($string, double_encode: false); // // Same as // htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, 'UTF-8', false); // [/php] // [/example] // Passing the same parameter multiple times results in an Error exception. // [example] // Example #18 Error thrown when passing the same parameter multiple times // [php] // function foo($param) { ... } // // foo(param: 1, param: 2); // // Error: Named parameter $param overwrites previous argument // foo(1, param: 2); // // Error: Named parameter $param overwrites previous argument // [/php] // [/example] // As of PHP 8.1.0, it is possible to use named arguments after unpacking the arguments. A named argument must not override an already unpacked argument. // [example] // Example #19 Use named arguments after unpacking // [php] // function foo($a, $b, $c = 3, $d = 4) { // return $a + $b + $c + $d; // } // // var_dump(foo(...[1, 2], d: 40)); // 46 // var_dump(foo(...['b' => 2, 'a' => 1], d: 40)); // 46 // // var_dump(foo(...[1, 2], b: 20)); // Fatal error. Named parameter $b overwrites previous argument // [/php] // [/example] // // ===== LITERATURE_SOURCES // * PHP_NET (2023-11-11) // URL: https://www.php.net/manual/en/functions.arguments.php // FUNCTION_ARGUMENTS - END // // RETURNING_VALUES - BEGIN // Returning values // // Values are returned by using the optional return statement. Any type may be returned, including arrays and objects. This causes the function to end its execution immediately and pass control back to the line from which it was called. See return for more information. // Note: If the return is omitted the value null will be returned. // [example] // Use of return // Example #1 Use of return // [php] // function square($num) // { // return $num * $num; // } // echo square(4); // outputs '16'. // [/php] // [/example] // A function can not return multiple values, but similar results can be obtained by returning an array. // [example] // Example #2 Returning an array to get multiple values // [php] // function small_numbers() // { // return [0, 1, 2]; // } // // Array destructuring will collect each member of the array individually // [$zero, $one, $two] = small_numbers(); // // // Prior to 7.1.0, the only equivalent alternative is using list() construct // list($zero, $one, $two) = small_numbers(); // // [/php] // [/example] // To return a reference from a function, use the reference operator & in both the function declaration and when assigning the returned value to a variable: // [example] // Example #3 Returning a reference from a function // [php] // function &returns_reference() // { // return $someref; // } // // $newref =& returns_reference(); // [/php] // [/example] // For more information on references, please check out References Explained. // // ===== LITERATURE_SOURCES // * PHP_NET (2023-11-11) // URL: https://www.php.net/manual/en/functions.returning-values.php // RETURNING_VALUES - END // // VARIABLE_FUNCTIONS - BEGIN // Variable functions // // PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth. // Variable functions won't work with language constructs such as echo, print, unset(), isset(), empty(), include, require and the like. Utilize wrapper functions to make use of any of these constructs as variable functions. // [example] // Example #1 Variable function example // [php] // function foo() { // echo "In foo()
\n"; // } // // function bar($arg = '') // { // echo "In bar(); argument was '$arg'.
\n"; // } // // // This is a wrapper function around echo // function echoit($string) // { // echo $string; // } // // $func = 'foo'; // $func(); // This calls foo() // // $func = 'bar'; // $func('test'); // This calls bar() // // $func = 'echoit'; // $func('test'); // This calls echoit() // [/php] // [/example] // Object methods can also be called with the variable functions syntax. // [example] // Example #2 Variable method example // [php] // class Foo // { // function Variable() // { // $name = 'Bar'; // $this->$name(); // This calls the Bar() method // } // // function Bar() // { // echo "This is Bar"; // } // } // // $foo = new Foo(); // $funcname = "Variable"; // $foo->$funcname(); // This calls $foo->Variable() // // [/php] // [/example] // When calling static methods, the function call is stronger than the static property operator: // [example] // Example #3 Variable method example with static properties // [php] // class Foo // { // static $variable = 'static property'; // static function Variable() // { // echo 'Method Variable called'; // } // } // // echo Foo::$variable; // This prints 'static property'. It does need a $variable in this scope. // $variable = "Variable"; // Foo::$variable(); // This calls $foo->Variable() reading $variable in this scope. // // [/php] // [/example] // [example] // Example #4 Complex callables // [php] // class Foo // { // static function bar() // { // echo "bar\n"; // } // function baz() // { // echo "baz\n"; // } // } // // $func = array("Foo", "bar"); // $func(); // prints "bar" // $func = array(new Foo, "baz"); // $func(); // prints "baz" // $func = "Foo::bar"; // $func(); // prints "bar" // [/php] // [/example] // // ===== LITERATURE_SOURCES // * PHP_NET (2023-11-11) // URL: https://www.php.net/manual/en/functions.variable-functions.php // VARIABLE_FUNCTIONS - END // // INTERNAL_BUILT_IN_FUNCTIONS - BEGIN // Internal (built-in) functions // // PHP comes standard with many functions and constructs. There are also functions that require specific PHP extensions compiled in, otherwise fatal "undefined function" errors will appear. For example, to use image functions such as imagecreatetruecolor(), PHP must be compiled with GD support. Or, to use mysqli_connect(), PHP must be compiled with MySQLi support. There are many core functions that are included in every version of PHP, such as the string and variable functions. A call to phpinfo() or get_loaded_extensions() will show which extensions are loaded into PHP. Also note that many extensions are enabled by default and that the PHP manual is split up by extension. See the configuration, installation, and individual extension chapters, for information on how to set up PHP. // Reading and understanding a function's prototype is explained within the manual section titled how to read a function definition. It's important to realize what a function returns or if a function works directly on a passed in value. For example, str_replace() will return the modified string while usort() works on the actual passed in variable itself. Each manual page also has specific information for each function like information on function parameters, behavior changes, return values for both success and failure, and availability information. Knowing these important (yet often subtle) differences is crucial for writing correct PHP code. // Note: If the parameters given to a function are not what it expects, such as passing an array where a string is expected, the return value of the function is undefined. In this case it will likely return null but this is just a convention, and cannot be relied upon. As of PHP 8.0.0, a TypeError exception is supposed to be thrown in this case. // Note: // Scalar types for built-in functions are nullable by default in coercive mode. As of PHP 8.1.0, passing null to an internal function parameter that is not declared nullable is discouraged and emits a deprecation notice in coercive mode to align with the behavior of user-defined functions, where scalar types need to be marked as nullable explicitly. // [example] // For example, strlen() function expects the parameter $string to be a non-nullable string. For historical reasons, PHP allows passing null for this parameter in coercive mode, and the parameter is implicitly cast to string, resulting in a "" value. In contrast, a TypeError is emitted in strict mode. // [php] // var_dump(strlen(null)); // // "Deprecated: Passing null to parameter #1 ($string) of type string is deprecated" as of PHP 8.1.0 // // int(0) // // var_dump(str_contains("foobar", null)); // // "Deprecated: Passing null to parameter #2 ($needle) of type string is deprecated" as of PHP 8.1.0 // // bool(true) // [/php] // [/example] // // ===== LITERATURE_SOURCES // * PHP_NET (2023-11-11) // URL: https://www.php.net/manual/en/functions.internal.php // INTERNAL_BUILT_IN_FUNCTIONS - END // // ANONYMOUS_FUNCTIONS - BEGIN // Anonymous functions // // Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses. // Anonymous functions are implemented using the Closure class. // [example] // Example #1 Anonymous function example // [php] // echo preg_replace_callback('~-([a-z])~', function ($match) { // return strtoupper($match[1]); // }, 'hello-world'); // // outputs helloWorld // [/php] // [/example] // Closures can also be used as the values of variables; PHP automatically converts such expressions into instances of the Closure internal class. Assigning a closure to a variable uses the same syntax as any other assignment, including the trailing semicolon: // [example] // Example #2 Anonymous function variable assignment example // [php] // $greet = function($name) { // printf("Hello %s\r\n", $name); // }; // // $greet('World'); // $greet('PHP'); // [/php] // [/example] // Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct. As of PHP 7.1, these variables must not include superglobals, $this, or variables with the same name as a parameter. A return type declaration of the function has to be placed after the use clause. // [example] // Example #3 Inheriting variables from the parent scope // [php] // $message = 'hello'; // // // No "use" // $example = function () { // var_dump($message); // }; // $example(); // // // Inherit $message // $example = function () use ($message) { // var_dump($message); // }; // $example(); // // // Inherited variable's value is from when the function // // is defined, not when called // $message = 'world'; // $example(); // // // Reset message // $message = 'hello'; // // // Inherit by-reference // $example = function () use (&$message) { // var_dump($message); // }; // $example(); // // // The changed value in the parent scope // // is reflected inside the function call // $message = 'world'; // $example(); // // // Closures can also accept regular arguments // $example = function ($arg) use ($message) { // var_dump($arg . ' ' . $message); // }; // $example("hello"); // // // Return type declaration comes after the use clause // $example = function () use ($message): string { // return "hello $message"; // }; // var_dump($example()); // [/php] // The above example will output something similar to: // [result] // Notice: Undefined variable: message in /example.php on line 6 // NULL // string(5) "hello" // string(5) "hello" // string(5) "hello" // string(5) "world" // string(11) "hello world" // string(11) "hello world" // [/result] // [/example] // As of PHP 8.0.0, the list of scope-inherited variables may include a trailing comma, which will be ignored. // Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from). See the following example: // [example] // Example #4 Closures and scoping // [php] // // A basic shopping cart which contains a list of added products // // and the quantity of each product. Includes a method which // // calculates the total price of the items in the cart using a // // closure as a callback. // 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); // } // } // // $my_cart = new Cart; // // // Add some items to the cart // $my_cart->add('butter', 1); // $my_cart->add('milk', 3); // $my_cart->add('eggs', 6); // // // Print the total with a 5% sales tax. // print $my_cart->getTotal(0.05) . "\n"; // // The result is 54.29 // // [/php] // [/example] // [example] // Example #5 Automatic binding of $this // [php] // // class Test // { // public function testing() // { // return function() { // var_dump($this); // }; // } // } // // $object = new Test; // $function = $object->testing(); // $function(); // // [/php] // The above example will output: // [result] // object(Test)#1 (0) { // } // [/result] // [/example] // When declared in the context of a class, the current class is automatically bound to it, making $this available inside of the function's scope. If this automatic binding of the current class is not wanted, then static anonymous functions may be used instead. // // Static anonymous functions // Anonymous functions may be declared statically. This prevents them from having the current class automatically bound to them. Objects may also not be bound to them at runtime. // [example] // Example #6 Attempting to use $this inside a static anonymous function // [php] // // class Foo // { // function __construct() // { // $func = static function() { // var_dump($this); // }; // $func(); // } // }; // new Foo(); // // [/php] // The above example will output: // [result] // Notice: Undefined variable: this in %s on line %d // NULL // [/result] // [/example] // [example] // Example #7 Attempting to bind an object to a static anonymous function // [php] // // $func = static function() { // // function body // }; // $func = $func->bindTo(new stdClass); // $func(); // // [/php] // The above example will output: // [result] // Warning: Cannot bind an instance to a static closure in %s on line %d // [/result] // [/example] // // Changelog // Version - Description // 7.1.0 - Anonymous functions may not close over superglobals, $this, or any variable with the same name as a parameter. // // Notes // Note: It is possible to use func_num_args(), func_get_arg(), and func_get_args() from within a closure. // // ===== LITERATURE_SOURCES // * PHP_NET (2023-11-11) // URL: https://www.php.net/manual/en/functions.anonymous.php // ANONYMOUS_FUNCTIONS - END // // ARROW_FUNCTIONS - BEGIN // Arrow Functions // // Arrow functions were introduced in PHP 7.4 as a more concise syntax for anonymous functions. // Both anonymous functions and arrow functions are implemented using the Closure class. // Arrow functions have the basic form fn (argument_list) => expr. // Arrow functions support the same features as anonymous functions, except that using variables from the parent scope is always automatic. // When a variable used in the expression is defined in the parent scope it will be implicitly captured by-value. In the following example, the functions $fn1 and $fn2 behave the same way. // [example] // Example #1 Arrow functions capture variables by value automatically // [php] // // $y = 1; // // $fn1 = fn($x) => $x + $y; // // equivalent to using $y by value: // $fn2 = function ($x) use ($y) { // return $x + $y; // }; // // var_export($fn1(3)); // [/php] // The above example will output: // [result] // 4 // [/result] // [/example] // This also works if the arrow functions are nested: // [example] // Example #2 Arrow functions capture variables by value automatically, even when nested // [php] // // $z = 1; // $fn = fn($x) => fn($y) => $x * $y + $z; // // Outputs 51 // var_export($fn(5)(10)); // [/php] // [/example] // Similarly to anonymous functions, the arrow function syntax allows arbitrary function signatures, including parameter and return types, default values, variadics, as well as by-reference passing and returning. All of the following are valid examples of arrow functions: // [example] // Example #3 Examples of arrow functions // [php] // // fn(array $x) => $x; // static fn(): int => $x; // fn($x = 42) => $x; // fn(&$x) => $x; // fn&($x) => $x; // fn($x, ...$rest) => $rest; // // [/php] // [/example] // Arrow functions use by-value variable binding. This is roughly equivalent to performing a use($x) for every variable $x used inside the arrow function. A by-value binding means that it is not possible to modify any values from the outer scope. Anonymous functions can be used instead for by-ref bindings. // [example] // Example #4 Values from the outer scope cannot be modified by arrow functions // [php] // // $x = 1; // $fn = fn() => $x++; // Has no effect // $fn(); // var_export($x); // Outputs 1 // // [/php] // [/example] // // Changelog // Version - Description // 7.4.0 - Arrow functions became available. // // Notes // Note: It is possible to use func_num_args(), func_get_arg(), and func_get_args() from within an arrow function. // // ===== LITERATURE_SOURCES // * PHP_NET (2023-11-11) // URL: https://www.php.net/manual/en/functions.arrow.php // ARROW_FUNCTIONS - END // // FIRST_CLASS_CALLABLE_SYNTAX - BEGIN // First class callable syntax // // The first class callable syntax is introduced as of PHP 8.1.0, as a way of creating anonymous functions from callable. It supersedes existing callable syntax using strings and arrays. The advantage of this syntax is that it is accessible to static analysis, and uses the scope at the point where the callable is acquired. // CallableExpr(...) syntax is used to create a Closure object from callable. CallableExpr accepts any expression that can be directly called in the PHP grammar: // [example] // Example #1 Simple first class callable syntax // [php] // // class Foo { // public function method() {} // public static function staticmethod() {} // public function __invoke() {} // } // // $obj = new Foo(); // $classStr = 'Foo'; // $methodStr = 'method'; // $staticmethodStr = 'staticmethod'; // // // $f1 = strlen(...); // $f2 = $obj(...); // invokable object // $f3 = $obj->method(...); // $f4 = $obj->$methodStr(...); // $f5 = Foo::staticmethod(...); // $f6 = $classStr::$staticmethodStr(...); // // // traditional callable using string, array // $f7 = 'strlen'(...); // $f8 = [$obj, 'method'](...); // $f9 = [Foo::class, 'staticmethod'](...); // [/php] // [/example] // Note: The ... is part of the syntax, and not an omission. // CallableExpr(...) has the same semantics as Closure::fromCallable(). That is, unlike callable using strings and arrays, CallableExpr(...) respects the scope at the point where it is created: // [example] // Example #2 Scope comparison of CallableExpr(...) and traditional callable // [php] // // class Foo { // public function getPrivateMethod() { // return [$this, 'privateMethod']; // } // // private function privateMethod() { // echo __METHOD__, "\n"; // } // } // // $foo = new Foo; // $privateMethod = $foo->getPrivateMethod(); // $privateMethod(); // // Fatal error: Call to private method Foo::privateMethod() from global scope // // This is because call is performed outside from Foo and visibility will be checked from this point. // // class Foo1 { // public function getPrivateMethod() { // // Uses the scope where the callable is acquired. // return $this->privateMethod(...); // identical to Closure::fromCallable([$this, 'privateMethod']); // } // // private function privateMethod() { // echo __METHOD__, "\n"; // } // } // // $foo1 = new Foo1; // $privateMethod = $foo1->getPrivateMethod(); // $privateMethod(); // Foo1::privateMethod // [/php] // [/example] // Note: Object creation by this syntax (e.g new Foo(...)) is not supported, because new Foo() syntax is not considered a call. // Note: // The first-class callable syntax cannot be combined with the nullsafe operator. Both of the following result in a compile-time error: // [php] // $obj?->method(...); // $obj?->prop->method(...); // [/php] // // ===== LITERATURE_SOURCES // * PHP_NET (2023-11-11) // URL: https://www.php.net/manual/en/functions.first_class_callable_syntax.php // FIRST_CLASS_CALLABLE_SYNTAX - END // // ===== LITERATURE_SOURCES // * PHP_NET (2023-11-11) // URL: https://www.php.net/manual/en/language.functions.php // LANGUAGE_REFERENCE_FUNCTIONS - END // ============================== // ============================== BEGIN // PHP_VARIABLE_FUNCTIONHANDLING_CALL_USER_FUNC_ARRAY // ============================== PUBLIC // ============================== ABOUT // Call a callback with an array of parameters. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // call_user_func_array() - PHP_4 >= PHP_4_0_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_functionhandling_call_user_func_array($callback, $args) { $return_call_user_func_array = null; // ========== CALL_USER_FUNC_ARRAY - BEGIN // ===== ABOUT // Call a callback with an array of parameters // ===== DESCRIPTION // Calls the callback given by the first parameter with the parameters in args. // ===== SUPPORTED // PHP_4 >= PHP_4_0_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // call_user_func_array(callable $callback, array $args): mixed // ===== CODE $return_call_user_func_array = call_user_func_array( $callback, // callable callback - The callable to be called. $args // array args - The parameters to be passed to the callback, as an array. // If the keys of args are all numeric, the keys are ignored and each element will be passed to callback as a positional argument, in order. // If any keys of args are strings, those elements will be passed to callback as named arguments, with the name given by the key. // It is a fatal error to have a numeric key in args appear after a string key, or to have a string key that does not match the name of any parameter of callback. ); // Return Values // Returns the return value of the callback, or false on error. // // Changelog // Version - Description // 8.0.0 - args keys will now be interpreted as parameter names, instead of being silently ignored. // // [examples] // Examples // [example] // Example #1 call_user_func_array() example // [php] // function foobar($arg, $arg2) { // echo __FUNCTION__, " got $arg and $arg2\n"; // } // class foo { // function bar($arg, $arg2) { // echo __METHOD__, " got $arg and $arg2\n"; // } // } // // // // Call the foobar() function with 2 arguments // call_user_func_array("foobar", array("one", "two")); // // // Call the $foo->bar() method with 2 arguments // $foo = new foo; // call_user_func_array(array($foo, "bar"), array("three", "four")); // [/php] // The above example will output something similar to: // [result] // foobar got one and two // foo::bar got three and four // [/result] // [/example] // [example] // Example #2 call_user_func_array() using namespace name // [php] // // namespace Foobar; // // class Foo { // static public function test($name) { // print "Hello {$name}!\n"; // } // } // // call_user_func_array(__NAMESPACE__ .'\Foo::test', array('Hannes')); // // call_user_func_array(array(__NAMESPACE__ .'\Foo', 'test'), array('Philip')); // // [/php] // The above example will output something similar to: // [result] // Hello Hannes! // Hello Philip! // [/result] // [/example] // [example] // Example #3 Using lambda function // [php] // // $func = function($arg1, $arg2) { // return $arg1 * $arg2; // }; // // var_dump(call_user_func_array($func, array(2, 4))); // // [/php] // The above example will output: // [result] // int(8) // [/result] // [/example] // [example] // Example #4 Passing values by reference // [php] // // function mega(&$a){ // $a = 55; // echo "function mega \$a=$a\n"; // } // $bar = 77; // call_user_func_array('mega',array(&$bar)); // echo "global \$bar=$bar\n"; // // [/php] // The above example will output: // [result] // function mega $a=55 // global $bar=55 // [/result] // [/example] // [example] // Example #5 call_user_func_array() using named arguments // [php] // function foobar($first, $second) { // echo __FUNCTION__, " got $first and $second\n"; // } // // // Call the foobar() function with named arguments in non-positional order // call_user_func_array("foobar", array("second" => "two", "first" => "one")); // // // Call the foobar() function with one named argument // call_user_func_array("foobar", array("foo", "second" => "bar")); // // // Fatal error: Cannot use positional argument after named argument // call_user_func_array("foobar", array("first" => "one", "bar")); // // [/php] // The above example will output something similar to: // [result] // foobar got one and two // foobar got foo and bar // // Fatal error: Uncaught Error: Cannot use positional argument after named argument // [/result] // [/example] // [/examples] // // Notes // Note: Callbacks registered with functions such as call_user_func() and call_user_func_array() will not be called if there is an uncaught exception thrown in a previous callback. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-22) // URL: https://www.php.net/manual/en/function.call-user-func-array.php // ========== CALL_USER_FUNC_ARRAY - END // SYNTAX: // mixed call_user_func_array(callable $callback, array $args) return $return_call_user_func_array; // mixed } // ============================== END // PHP_VARIABLE_FUNCTIONHANDLING_CALL_USER_FUNC_ARRAY // ============================== // ============================== BEGIN // PHP_VARIABLE_FUNCTIONHANDLING_CALL_USER_FUNC // ============================== PUBLIC // ============================== ABOUT // Call the callback given by the first parameter. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // call_user_func() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_functionhandling_call_user_func($callback, $args) { $return_call_user_func = null; // ========== CALL_USER_FUNC - BEGIN // ===== ABOUT // Call the callback given by the first parameter // ===== DESCRIPTION // Calls the callback given by the first parameter and passes the remaining parameters as arguments. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // call_user_func(callable $callback, mixed ...$args): mixed // ===== CODE $return_call_user_func = call_user_func( $callback, // callable callback - The callable to be called. $args // mixed args - Zero or more parameters to be passed to the callback. // Note: // Note that the parameters for call_user_func() are not passed by reference. // [example] // Example #1 call_user_func() example and references // [php] // error_reporting(E_ALL); // function increment(&$var) // { // $var++; // } // // $a = 0; // call_user_func('increment', $a); // echo $a."\n"; // // // it is possible to use this instead // call_user_func_array('increment', array(&$a)); // echo $a."\n"; // // // it is also possible to use a variable function // $increment = 'increment'; // $increment($a); // echo $a."\n"; // [/php] // The above example will output: // [result] // Warning: Parameter 1 to increment() expected to be a reference, value given in … // 0 // 1 // 2 // [/result] // [/example] ); // Return Values // Returns the return value of the callback. // // [examples] // Examples // [example] // Example #2 call_user_func() example // [php] // function barber($type) // { // echo "You wanted a $type haircut, no problem\n"; // } // call_user_func('barber', "mushroom"); // call_user_func('barber', "shave"); // [/php] // The above example will output: // [result] // You wanted a mushroom haircut, no problem // You wanted a shave haircut, no problem // [/result] // [/example] // [example] // Example #3 call_user_func() using namespace name // [php] // // namespace Foobar; // // class Foo { // static public function test() { // print "Hello world!\n"; // } // } // // call_user_func(__NAMESPACE__ .'\Foo::test'); // call_user_func(array(__NAMESPACE__ .'\Foo', 'test')); // // [/php] // The above example will output: // [result] // Hello world! // Hello world! // [/result] // [/example] // [example] // Example #4 Using a class method with call_user_func() // [php] // // class myclass { // static function say_hello() // { // echo "Hello!\n"; // } // } // // $classname = "myclass"; // // call_user_func(array($classname, 'say_hello')); // call_user_func($classname .'::say_hello'); // // $myobject = new myclass(); // // call_user_func(array($myobject, 'say_hello')); // // [/php] // The above example will output: // [result] // Hello! // Hello! // Hello! // [/result] // [/example] // [example] // Example #5 Using lambda function with call_user_func() // [php] // call_user_func(function($arg) { print "[$arg]\n"; }, 'test'); // [/php] // The above example will output: // [result] // [test] // [/result] // [/example] // [/examples] // // Notes // Note: Callbacks registered with functions such as call_user_func() and call_user_func_array() will not be called if there is an uncaught exception thrown in a previous callback. // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-22) // URL: https://www.php.net/manual/en/function.call-user-func.php // ========== CALL_USER_FUNC - END // SYNTAX: // mixed call_user_func(callable $callback, mixed $args) return $return_call_user_func; // mixed } // ============================== END // PHP_VARIABLE_FUNCTIONHANDLING_CALL_USER_FUNC // ============================== // ============================== BEGIN // PHP_VARIABLE_FUNCTIONHANDLING_FORWARD_STATIC_CALL_ARRAY // ============================== OFFLINE // ============================== ABOUT // Call a static method and pass the arguments as array. // ============================== SUPPORT // PHP_5 PHP_8 // ============================== USING FUNCTIONS (1) // forward_static_call_array() - PHP_5 >= PHP_5_3_0, PHP_7, PHP_8 // ============================== CODE /* function php_variable_functionhandling_forward_static_call_array($callback, $args) { $return_forward_static_call_array = null; // ========== FORWARD_STATIC_CALL_ARRAY - BEGIN // ===== ABOUT // Call a static method and pass the arguments as array // ===== DESCRIPTION // Calls a user defined function or method given by the callback parameter. This function must be called within a method context, it can't be used outside a class. It uses the late static binding. All arguments of the forwarded method are passed as values, and as an array, similarly to call_user_func_array(). // ===== SUPPORTED // PHP_5 >= PHP_5_3_0, PHP_7, PHP_8 // ===== SYNTAX // forward_static_call_array(callable $callback, array $args): mixed // ===== CODE $return_forward_static_call_array = forward_static_call_array( $callback, // callable callback - The function or method to be called. This parameter may be an array, with the name of the class, and the method, or a string, with a function name. $args // array parameter - One parameter, gathering all the method parameter in one array. // Note: Note that the parameters for forward_static_call_array() are not passed by reference. ); // Return Values // Returns the function result, or false on error. // // [examples] // Examples // [example] // Example #1 forward_static_call_array() example // [php] // // class A // { // const NAME = 'A'; // public static function test() { // $args = func_get_args(); // echo static::NAME, " ".join(',', $args)." \n"; // } // } // // class B extends A // { // const NAME = 'B'; // // public static function test() { // echo self::NAME, "\n"; // forward_static_call_array(array('A', 'test'), array('more', 'args')); // forward_static_call_array( 'test', array('other', 'args')); // } // } // // B::test('foo'); // // function test() { // $args = func_get_args(); // echo "C ".join(',', $args)." \n"; // } // // [/php] // The above example will output: // [result] // B // B more,args // C other,args // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-23) // URL: https://www.php.net/manual/en/function.forward-static-call-array.php // ========== FORWARD_STATIC_CALL_ARRAY - END // SYNTAX: // mixed forward_static_call_array(callable $callback, array $args) return $return_forward_static_call_array; // mixed } */ // ============================== END // PHP_VARIABLE_FUNCTIONHANDLING_FORWARD_STATIC_CALL_ARRAY // ============================== // ============================== BEGIN // PHP_VARIABLE_FUNCTIONHANDLING_FORWARD_STATIC_CALL // ============================== OFFLINE // ============================== ABOUT // Call a static method. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // forward_static_call() - PHP_5 >= PHP_5_3_0, PHP_7, PHP_8 // ============================== CODE /* function php_variable_functionhandling_forward_static_call($callback, $args) { $return_forward_static_call = null; // ========== FORWARD_STATIC_CALL - BEGIN // ===== ABOUT // Call a static method // ===== DESCRIPTION // Calls a user defined function or method given by the callback parameter, with the following arguments. This function must be called within a method context, it can't be used outside a class. It uses the late static binding. // ===== SUPPORTED // PHP_5 >= PHP_5_3_0, PHP_7, PHP_8 // ===== SYNTAX // forward_static_call(callable $callback, mixed ...$args): mixed // ===== CODE $return_forward_static_call = forward_static_call( $callback, // callable callback - The function or method to be called. This parameter may be an array, with the name of the class, and the method, or a string, with a function name. $args // mixed args - Zero or more parameters to be passed to the function. ); // Return Values // Returns the function result, or false on error. // // [examples] // Examples // [example] // Example #1 forward_static_call() example // [php] // // class A // { // const NAME = 'A'; // public static function test() { // $args = func_get_args(); // echo static::NAME, " ".join(',', $args)." \n"; // } // } // // class B extends A // { // const NAME = 'B'; // // public static function test() { // echo self::NAME, "\n"; // forward_static_call(array('A', 'test'), 'more', 'args'); // forward_static_call( 'test', 'other', 'args'); // } // } // // B::test('foo'); // // function test() { // $args = func_get_args(); // echo "C ".join(',', $args)." \n"; // } // // [/php] // The above example will output: // [result] // B // B more,args // C other,args // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-23) // URL: https://www.php.net/manual/en/function.forward-static-call.php // ========== FORWARD_STATIC_CALL - END // SYNTAX: // mixed forward_static_call(callable $callback, mixed $args) return $return_forward_static_call; // mixed } */ // ============================== END // PHP_VARIABLE_FUNCTIONHANDLING_FORWARD_STATIC_CALL // ============================== // ============================== BEGIN // PHP_VARIABLE_FUNCTIONHANDLING_FUNC_GET_ARG // ============================== PUBLIC // ============================== ABOUT // Return an item from the argument list. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // func_get_arg() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_functionhandling_func_get_arg($position) { $return_func_get_arg = null; // ========== FUNC_GET_ARG - BEGIN // ===== ABOUT // Return an item from the argument list // ===== DESCRIPTION // Gets the specified argument from a user-defined function's argument list. // This function may be used in conjunction with func_get_args() and func_num_args() to allow user-defined functions to accept variable-length argument lists. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // func_get_arg(int $position): mixed // ===== CODE $return_func_get_arg = func_get_arg( $position // int position - The argument offset. Function arguments are counted starting from zero. ); // Return Values // Returns the specified argument, or false on error. // // Errors/Exceptions // Generates a warning if called from outside of a user-defined function, or if position is greater than the number of arguments actually passed. // // [examples] // Examples // [example] // Example #1 func_get_arg() example // [php] // function foo() // { // $numargs = func_num_args(); // echo "Number of arguments: $numargs\n"; // if ($numargs >= 2) { // echo "Second argument is: " . func_get_arg(1) . "\n"; // } // } // // foo(1, 2, 3); // [/php] // The above example will output: // [result] // Number of arguments: 3 // Second argument is: 2 // [/result] // [/example] // [example] // Example #2 func_get_arg() example of byref and byval arguments // [php] // function byVal($arg) { // echo 'As passed : ', var_export(func_get_arg(0)), PHP_EOL; // $arg = 'baz'; // echo 'After change : ', var_export(func_get_arg(0)), PHP_EOL; // } // // function byRef(&$arg) { // echo 'As passed : ', var_export(func_get_arg(0)), PHP_EOL; // $arg = 'baz'; // echo 'After change : ', var_export(func_get_arg(0)), PHP_EOL; // } // // $arg = 'bar'; // byVal($arg); // byRef($arg); // [/php] // The above example will output: // [result] // // As passed : 'bar' // After change : 'baz' // As passed : 'bar' // After change : 'baz' // [/result] // [/example] // [/examples] // // Notes // Note: As of PHP 8.0.0, the func_*() family of functions is intended to be mostly transparent with regard to named arguments, by treating the arguments as if they were all passed positionally, and missing arguments are replaced with their defaults. This function ignores the collection of unknown named variadic arguments. Unknown named arguments which are collected can only be accessed through the variadic parameter. // Note: If the arguments are passed by reference, any changes to the arguments will be reflected in the values returned by this function. As of PHP 7 the current values will also be returned if the arguments are passed by value. // Note: This function returns a copy of the passed arguments only, and does not account for default (non-passed) arguments. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-23) // URL: https://www.php.net/manual/en/function.func-get-arg.php // ========== FUNC_GET_ARG - END // SYNTAX: // mixed func_get_arg(int $position) return $return_func_get_arg; // mixed } // ============================== END // PHP_VARIABLE_FUNCTIONHANDLING_FUNC_GET_ARG // ============================== // ============================== BEGIN // PHP_VARIABLE_FUNCTIONHANDLING_FUNC_GET_ARGS // ============================== PUBLIC // ============================== ABOUT // Returns an array comprising a function's argument list. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // func_get_args() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_functionhandling_func_get_args() { $return_func_get_args = null; // ========== FUNC_GET_ARGS - BEGIN // ===== ABOUT // Returns an array comprising a function's argument list // ===== DESCRIPTION // Gets an array of the function's argument list. // This function may be used in conjunction with func_get_arg() and func_num_args() to allow user-defined functions to accept variable-length argument lists. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // func_get_args(): array // ===== CODE $return_func_get_args = func_get_args( // This function has no parameters. ); // Return Values // Returns an array in which each element is a copy of the corresponding member of the current user-defined function's argument list. // // Errors/Exceptions // Generates a warning if called from outside of a user-defined function. // // [examples] // Examples // [example] // Example #1 func_get_args() example // [php] // function foo() // { // $numargs = func_num_args(); // echo "Number of arguments: $numargs \n"; // if ($numargs >= 2) { // echo "Second argument is: " . func_get_arg(1) . "\n"; // } // $arg_list = func_get_args(); // for ($i = 0; $i < $numargs; $i++) { // echo "Argument $i is: " . $arg_list[$i] . "\n"; // } // } // // foo(1, 2, 3); // [/php] // The above example will output: // [result] // Number of arguments: 3 // Second argument is: 2 // Argument 0 is: 1 // Argument 1 is: 2 // Argument 2 is: 3 // [/result] // [/example] // [example] // Example #2 func_get_args() example of byref and byval arguments // [php] // function byVal($arg) { // echo 'As passed : ', var_export(func_get_args()), PHP_EOL; // $arg = 'baz'; // echo 'After change : ', var_export(func_get_args()), PHP_EOL; // } // // function byRef(&$arg) { // echo 'As passed : ', var_export(func_get_args()), PHP_EOL; // $arg = 'baz'; // echo 'After change : ', var_export(func_get_args()), PHP_EOL; // } // // $arg = 'bar'; // byVal($arg); // byRef($arg); // [/php] // The above example will output: // [result] // // As passed : array ( // 0 => 'bar', // ) // After change : array ( // 0 => 'baz', // ) // As passed : array ( // 0 => 'bar', // ) // After change : array ( // 0 => 'baz', // ) // [/result] // [/example] // [/examples] // // Notes // Note: As of PHP 8.0.0, the func_*() family of functions is intended to be mostly transparent with regard to named arguments, by treating the arguments as if they were all passed positionally, and missing arguments are replaced with their defaults. This function ignores the collection of unknown named variadic arguments. Unknown named arguments which are collected can only be accessed through the variadic parameter. // Note: If the arguments are passed by reference, any changes to the arguments will be reflected in the values returned by this function. As of PHP 7 the current values will also be returned if the arguments are passed by value. // Note: This function returns a copy of the passed arguments only, and does not account for default (non-passed) arguments. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-23) // URL: https://www.php.net/manual/en/function.func-get-args.php // ========== FUNC_GET_ARGS - END // SYNTAX: // array func_get_args() return $return_func_get_args; // array } // ============================== END // PHP_VARIABLE_FUNCTIONHANDLING_FUNC_GET_ARGS // ============================== // ============================== BEGIN // PHP_VARIABLE_FUNCTIONHANDLING_FUNC_NUM_ARGS // ============================== PUBLIC // ============================== ABOUT // Returns the number of arguments passed to the function. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // func_num_args() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_functionhandling_func_num_args() { $return_func_num_args = 0; // ========== FUNC_NUM_ARGS - BEGIN // ===== ABOUT // Returns the number of arguments passed to the function // ===== DESCRIPTION // Gets the number of arguments passed to the function. // This function may be used in conjunction with func_get_arg() and func_get_args() to allow user-defined functions to accept variable-length argument lists. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // func_num_args(): int // ===== CODE $return_func_num_args = func_num_args( // This function has no parameters. ); // Return Values // Returns the number of arguments passed into the current user-defined function. // // Errors/Exceptions // Generates a warning if called from outside of a user-defined function. // // [examples] // Examples // [example] // Example #1 func_num_args() example // [php] // function foo() // { // echo "Number of arguments: ", func_num_args(), PHP_EOL; // } // // foo(1, 2, 3); // [/php] // The above example will output: // [result] // Number of arguments: 3 // [/result] // [/example] // [/examples] // // Notes // Note: As of PHP 8.0.0, the func_*() family of functions is intended to be mostly transparent with regard to named arguments, by treating the arguments as if they were all passed positionally, and missing arguments are replaced with their defaults. This function ignores the collection of unknown named variadic arguments. Unknown named arguments which are collected can only be accessed through the variadic parameter. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-23) // URL: https://www.php.net/manual/en/function.func-num-args.php // ========== FUNC_NUM_ARGS - END // SYNTAX: // int func_num_args() return $return_func_num_args; // int } // ============================== END // PHP_VARIABLE_FUNCTIONHANDLING_FUNC_NUM_ARGS // ============================== // ============================== BEGIN // PHP_VARIABLE_FUNCTIONHANDLING_FUNCTION_EXISTS // ============================== PUBLIC // ============================== ABOUT // Return true if the given function has been defined // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // function_exists() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_functionhandling_function_exists($function) { $return_function_exists = false; // ========== FUNCTION_EXISTS - BEGIN // ===== ABOUT // Return true if the given function has been defined // ===== DESCRIPTION // Checks the list of defined functions, both built-in (internal) and user-defined, for function. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // function_exists(string $function): bool // ===== CODE $return_function_exists = function_exists( $function // string function - The function name, as a string. ); // Return Values // Returns true if function exists and is a function, false otherwise. // Note: This function will return false for constructs, such as include_once and echo. // // [examples] // Examples // [example] // Example #1 function_exists() example // [php] // if (function_exists('imap_open')) { // echo "IMAP functions are available.
\n"; // } else { // echo "IMAP functions are not available.
\n"; // } // [/php] // [/example] // [/examples] // // Notes // Note: A function name may exist even if the function itself is unusable due to configuration or compiling options (with the image functions being an example). // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-23) // URL: https://www.php.net/manual/en/function.function-exists.php // ========== FUNCTION_EXISTS - END // SYNTAX: // bool function_exists(string $function) return $return_function_exists; // bool } // ============================== END // PHP_VARIABLE_FUNCTIONHANDLING_FUNCTION_EXISTS // ============================== // ============================== BEGIN // PHP_VARIABLE_FUNCTIONHANDLING_GET_DEFINED_FUNCTIONS // ============================== PUBLIC // ============================== ABOUT // Returns an array of all defined functions. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // get_defined_functions() - PHP_4 >= PHP_4_0_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_functionhandling_get_defined_functions($exclude_disabled = true) { $return_get_defined_functions = null; // ========== GET_DEFINED_FUNCTIONS - BEGIN // ===== ABOUT // Returns an array of all defined functions // ===== DESCRIPTION // Gets an array of all defined functions. // ===== SUPPORTED // PHP_4 >= PHP_4_0_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // get_defined_functions(bool $exclude_disabled = true): array // ===== CODE $return_get_defined_functions = get_defined_functions( $exclude_disabled // bool exclude_disabled - Whether disabled functions should be excluded from the return value. ); // Return Values // Returns a multidimensional array containing a list of all defined functions, both built-in (internal) and user-defined. The internal functions will be accessible via $arr["internal"], and the user defined ones using $arr["user"] (see example below). // // Changelog // Version - Description // 8.0.0 - The default value of the exclude_disabled parameter has been changed from false to true. // 7.0.15, 7.1.1 - The exclude_disabled parameter has been added. // // [examples] // Examples // [example] // Example #1 get_defined_functions() example // [php] // function myrow($id, $data) // { // return "$id$data\n"; // } // // $arr = get_defined_functions(); // // print_r($arr); // [/php] // The above example will output something similar to: // [result] // Array // ( // [internal] => Array // ( // [0] => zend_version // [1] => func_num_args // [2] => func_get_arg // [3] => func_get_args // [4] => strlen // [5] => strcmp // [6] => strncmp // ... // [750] => bcscale // [751] => bccomp // ) // // [user] => Array // ( // [0] => myrow // ) // // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-23) // URL: https://www.php.net/manual/en/function.get-defined-functions.php // ========== GET_DEFINED_FUNCTIONS - END // SYNTAX: // array get_defined_functions(bool $exclude_disabled = true) return $return_get_defined_functions; // array } // ============================== END // PHP_VARIABLE_FUNCTIONHANDLING_GET_DEFINED_FUNCTIONS // ============================== // ============================== BEGIN // PHP_VARIABLE_FUNCTIONHANDLING_REGISTER_SHUTDOWN_FUNCTION // ============================== PUBLIC // ============================== ABOUT // Register a function for execution on shutdown. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // register_shutdown_function() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_functionhandling_register_shutdown_function($callback, $args) { // ========== REGISTER_SHUTDOWN_FUNCTION - BEGIN // ===== ABOUT // Register a function for execution on shutdown // ===== DESCRIPTION // Registers a callback to be executed after script execution finishes or exit() is called. // Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered. If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called. // Shutdown functions may also call register_shutdown_function() themselves to add a shutdown function to the end of the queue. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // register_shutdown_function(callable $callback, mixed ...$args): void // ===== CODE register_shutdown_function( $callback, // callable callback - The shutdown callback to register. // The shutdown callbacks are executed as the part of the request, so it's possible to send output from them and access output buffers. $args // mixed args - It is possible to pass parameters to the shutdown function by passing additional parameters. ); // Return Values // No value is returned. // // [examples] // Examples // [example] // Example #1 register_shutdown_function() example // [php] // function shutdown() // { // // This is our shutdown function, in // // here we can do any last operations // // before the script is complete. // // echo 'Script executed with success', PHP_EOL; // } // // register_shutdown_function('shutdown'); // [/php] // [/example] // [/examples] // // Notes // Note: The working directory of the script can change inside the shutdown function under some web servers, e.g. Apache. // Note: Shutdown functions will not be executed if the process is killed with a SIGTERM or SIGKILL signal. While you cannot intercept a SIGKILL, you can use pcntl_signal() to install a handler for a SIGTERM which uses exit() to end cleanly. // Note: Shutdown functions run separately from the time tracked by max_execution_time. That means even if a process is terminated for running too long, shutdown functions will still be called. Additionally, if the max_execution_time runs out while a shutdown function is running it will not be terminated. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-23) // URL: https://www.php.net/manual/en/function.register-shutdown-function.php // ========== REGISTER_SHUTDOWN_FUNCTION - END // SYNTAX: // void register_shutdown_function(callable $callback, mixed $args) // Return: void } // ============================== END // PHP_VARIABLE_FUNCTIONHANDLING_REGISTER_SHUTDOWN_FUNCTION // ============================== // ============================== BEGIN // PHP_VARIABLE_FUNCTIONHANDLING_REGISTER_TICK_FUNCTION // ============================== PUBLIC // ============================== ABOUT // Register a function for execution on each tick. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // register_tick_function() - PHP_4 >= PHP_4_0_3, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_functionhandling_register_tick_function($callback, $args) { $return_register_tick_function = false; // ========== REGISTER_TICK_FUNCTION - BEGIN // ===== ABOUT // Register a function for execution on each tick // ===== DESCRIPTION // Registers the given callback to be executed when a tick is called. // ===== SUPPORTED // PHP_4 >= PHP_4_0_3, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // register_tick_function(callable $callback, mixed ...$args): bool // ===== CODE $return_register_tick_function = register_tick_function( $callback, // callable callback - The function to register. $args // mixed args ); // Return Values // Returns true on success or false on failure. // // [examples] // Examples // [example] // Example #1 register_tick_function() example // [php] // declare(ticks=1); // // // using a function as the callback // register_tick_function('my_function', true); // // // using an object->method // $object = new my_class(); // register_tick_function(array($object, 'my_method'), true); // [/php] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-23) // URL: https://www.php.net/manual/en/function.register-tick-function.php // ========== REGISTER_TICK_FUNCTION - END // SYNTAX: // bool register_tick_function(callable $callback, mixed $args) return $return_register_tick_function; // bool } // ============================== END // PHP_VARIABLE_FUNCTIONHANDLING_REGISTER_TICK_FUNCTION // ============================== // ============================== BEGIN // PHP_VARIABLE_FUNCTIONHANDLING_UNREGISTER_TICK_FUNCTION // ============================== PUBLIC // ============================== ABOUT // De-register a function for execution on each tick. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // unregister_tick_function() - PHP_4 >= PHP_4_0_3, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_functionhandling_unregister_tick_function($callback) { // ========== UNREGISTER_TICK_FUNCTION - BEGIN // ===== ABOUT // De-register a function for execution on each tick // ===== DESCRIPTION // De-registers the function function so it is no longer executed when a tick is called. // ===== SUPPORTED // PHP_4 >= PHP_4_0_3, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // unregister_tick_function(callable $callback): void // ===== CODE unregister_tick_function( $callback // callable callback - The function to de-register. ); // Return Values // No value is returned. // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-22) // URL: https://www.php.net/manual/en/function.unregister-tick-function.php // ========== UNREGISTER_TICK_FUNCTION - END // SYNTAX: // void unregister_tick_function(callable $callback) // Return: void } // ============================== END // PHP_VARIABLE_FUNCTIONHANDLING_UNREGISTER_TICK_FUNCTION // ============================== // ============================== BEGIN // PHP_VARIABLE_FUNCTIONHANDLING_CREATE_FUNCTION // ============================== OFFLINE // ============================== ABOUT // Create a function dynamically by evaluating a string of code // // Warning: This function has been DEPRECATED as of PHP 7.2.0, and REMOVED as of PHP 8.0.0. Relying on this function is highly discouraged. // ============================== SUPPORT // PHP_4 - PHP_7 // ============================== USING FUNCTIONS (1) // create_function() - PHP_4 >= PHP_4_0_1, PHP_5, PHP_7 // ============================== CODE /* function php_variable_functionhandling_create_function($args, $code) { $return_create_function = null; // ========== CREATE_FUNCTION - BEGIN // ===== ABOUT // Create a function dynamically by evaluating a string of code // Warning: This function has been DEPRECATED as of PHP 7.2.0, and REMOVED as of PHP 8.0.0. Relying on this function is highly discouraged. // ===== DESCRIPTION // Creates a function dynamically from the parameters passed, and returns a unique name for it. // Caution: This function internally performs an eval() and as such has the same security issues as eval(). It also has bad performance and memory usage characteristics, because the created functions are global and can not be freed. // A native anonymous function should be used instead. // ===== SUPPORTED // PHP_4 >= PHP_4_0_1, PHP_5, PHP_7 // ===== SYNTAX // create_function(string $args, string $code): string // ===== CODE $return_create_function = create_function( // It is normally advisable to pass these parameters as single quoted strings. If using double quoted strings, variable names in the code need to be escaped carefully, e.g. \$somevar. $args, // string args - The function arguments, as a single comma-separated string. $code // string code - The function code. ); // Return Values // Returns a unique function name as a string, or false on failure. Note that the name contains a non-printable character ("\0"), so care should be taken when printing the name or incorporating it in any other string. // // [examples] // Examples // [example] // Example #1 Creating a function dynamically, with create_function() or anonymous functions // You can use a dynamically created function, to (for example) create a function from information gathered at run time. First, using create_function(): // [php] // $newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);'); // echo $newfunc(2, M_E) . "\n"; // [/php] // Now the same code, using an anonymous function; note that the code and arguments are no longer contained in strings: // [php] // $newfunc = function($a,$b) { return "ln($a) + ln($b) = " . log($a * $b); }; // echo $newfunc(2, M_E) . "\n"; // [/php] // The above example will output: // [result] // ln(2) + ln(2.718281828459) = 1.6931471805599 // [/result] // [/example] // [example] // Example #2 Making a general processing function, with create_function() or anonymous functions // Another use could be to have general handler function that can apply a set of operations to a list of parameters: // [php] // function process($var1, $var2, $farr) // { // foreach ($farr as $f) { // echo $f($var1, $var2) . "\n"; // } // } // // // create a bunch of math functions // $farr = array( // create_function('$x,$y', 'return "some trig: ".(sin($x) + $x*cos($y));'), // create_function('$x,$y', 'return "a hypotenuse: ".sqrt($x*$x + $y*$y);'), // create_function('$a,$b', 'if ($a >=0) {return "b*a^2 = ".$b*sqrt($a);} else {return false;}'), // create_function('$a,$b', "return \"min(b^2+a, a^2,b) = \".min(\$a*\$a+\$b,\$b*\$b+\$a);"), // create_function('$a,$b', 'if ($a > 0 && $b != 0) {return "ln(a)/b = ".log($a)/$b; } else { return false; }') // ); // // echo "\nUsing the first array of dynamic functions\n"; // echo "parameters: 2.3445, M_PI\n"; // process(2.3445, M_PI, $farr); // // // now make a bunch of string processing functions // $garr = array( // create_function('$b,$a', 'if (strncmp($a, $b, 3) == 0) return "** \"$a\" '. // 'and \"$b\"\n** Look the same to me! (looking at the first 3 chars)";'), // create_function('$a,$b', 'return "CRCs: " . crc32($a) . ", ".crc32($b);'), // create_function('$a,$b', 'return "similar(a,b) = " . similar_text($a, $b, $p) . "($p%)";') // ); // echo "\nUsing the second array of dynamic functions\n"; // process("Twas brilling and the slithy toves", "Twas the night", $garr); // [/php] // Again, here is the same code using anonymous functions. Note that variable names in the code no longer need to be escaped, because they are not enclosed in a string. // [php] // function process($var1, $var2, $farr) // { // foreach ($farr as $f) { // echo $f($var1, $var2) . "\n"; // } // } // // // create a bunch of math functions // $farr = array( // function($x,$y) { return "some trig: ".(sin($x) + $x*cos($y)); }, // function($x,$y) { return "a hypotenuse: ".sqrt($x*$x + $y*$y); }, // function($a,$b) { if ($a >=0) {return "b*a^2 = ".$b*sqrt($a);} else {return false;} }, // function($a,$b) { return "min(b^2+a, a^2,b) = " . min($a*$a+$b, $b*$b+$a); }, // function($a,$b) { if ($a > 0 && $b != 0) {return "ln(a)/b = ".log($a)/$b; } else { return false; } } // ); // // echo "\nUsing the first array of dynamic functions\n"; // echo "parameters: 2.3445, M_PI\n"; // process(2.3445, M_PI, $farr); // // // now make a bunch of string processing functions // $garr = array( // function($b,$a) { if (strncmp($a, $b, 3) == 0) return "** \"$a\" " . // "and \"$b\"\n** Look the same to me! (looking at the first 3 chars)"; }, // function($a,$b) { return "CRCs: " . crc32($a) . ", ".crc32($b); }, // function($a,$b) { return "similar(a,b) = " . similar_text($a, $b, $p) . "($p%)"; } // ); // echo "\nUsing the second array of dynamic functions\n"; // process("Twas brilling and the slithy toves", "Twas the night", $garr); // [/php] // The above example will output: // [result] // Using the first array of dynamic functions // parameters: 2.3445, M_PI // some trig: -1.6291725057799 // a hypotenuse: 3.9199852871011 // b*a^2 = 4.8103313314525 // min(b^2+a, a^2,b) = 8.6382729035898 // ln(a)/b = 0.27122299212594 // // Using the second array of dynamic functions // ** "Twas the night" and "Twas brilling and the slithy toves" // ** Look the same to me! (looking at the first 3 chars) // CRCs: 3569586014, 342550513 // similar(a,b) = 11(45.833333333333%) // [/result] // [/example] // [example] // Example #3 Using dynamic functions as callback functions // Perhaps the most common use for dynamic functions is to pass them as callbacks, for example when using array_walk() or usort(). // [php] // $av = array("the ", "a ", "that ", "this "); // array_walk($av, create_function('&$v,$k', '$v = $v . "mango";')); // print_r($av); // [/php] // Converted to an anonymous function: // [php] // $av = array("the ", "a ", "that ", "this "); // array_walk($av, function(&$v,$k) { $v = $v . "mango"; }); // print_r($av); // [/php] // The above example will output: // [result] // Array // ( // [0] => the mango // [1] => a mango // [2] => that mango // [3] => this mango // ) // [/result] // Sorting strings from longest to shortest with create_function(): // [php] // $sv = array("small", "a big string", "larger", "it is a string thing"); // echo "Original:\n"; // print_r($sv); // echo "Sorted:\n"; // usort($sv, create_function('$a,$b','return strlen($b) - strlen($a);')); // print_r($sv); // [/php] // Converted to an anonymous function: // [php] // $sv = array("small", "a big string", "larger", "it is a string thing"); // echo "Original:\n"; // print_r($sv); // echo "Sorted:\n"; // usort($sv, function($a,$b) { return strlen($b) - strlen($a); }); // print_r($sv); // [/php] // The above example will output: // [result] // Original: // Array // ( // [0] => small // [1] => a big string // [2] => larger // [3] => it is a string thing // ) // Sorted: // Array // ( // [0] => it is a string thing // [1] => a big string // [2] => larger // [3] => small // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-23) // URL: https://www.php.net/manual/en/function.create-function.php // ========== CREATE_FUNCTION - END // SYNTAX: // string create_function(string $args, string $code) return $return_create_function; // string } */ // ============================== END // PHP_VARIABLE_FUNCTIONHANDLING_CREATE_FUNCTION // ============================== // ============================== END // PHP_VARIABLE_FUNCTIONHANDLING // ============================== ?>