- BASICS
- Quotes
- Constants
- Control Structures
- Reference
- Number Systems
- VARIABLES
- Definition
- Variable Variable
- Exists
- Type Casting
- OPERATORS
- Aritmetic
- Bitwise
- String
- Comparison
- Logical
- FUNCTION
- Definition
-
Anonymous
- Reference
- Variable Arguments
- ARRAY
- Basics
- Operations
- Create
- Search
- Modify
- Sort
- Storage
- STRING
- String Basics
- String Compare
- String Search
- String Replace
- String Format
- String Regexp
- String Parse
- Formating
- Json
- STREAMS
- File Open
- Read File
- Read Csv
- File Contents
- Context
- Ob_start
- OOP
- Object Instantiation
- Class Constructor
- Interfaces
- Resource Visibility
- Class Constants
- Namespaces
- HTTP
- Headers
- File Uploads
- Cookies
- Sessions
PHP PAGES - LEVEL 1
Anonymous
/**
* An anonymous function is a function without a name.
* There are also called closures or lamba functions.
* Be aware of the ; after function declaration.
*/
$greet = function($name) {
return "Hello, $name!";
};
echo $greet('Alice'); // Hello, Alice!
Import variables
/**
* Anonymous function can inherit variables from the parent scope,
* using the keyword 'use'.
*/
$message = "Welcome";
$greet = function($name) use ($message) {
return "$message, $name!";
};
echo $greet("Alice"); // Welcome, Alice!
Callbacks
/**
* Closure are useful when using callbacks.
* They're ofthen used in function like array_map, array_filter.
*/
$numbers = [1, 2, 3];
$squares = array_map(function($n) {
return $n * $n;
}, $numbers);
print_r($squares); // 1, 4, 9
$evens = array_filter($numbers, function($n) {
return $n % 2 == 0;
});
print_r($evens); // 2
Arrow functions
/**
* Arrow functions provide a shorter syntax for one-line anonymous functions.
* Arrow functions automatically inherit variables from the parent scope.
*/
$numbers = [1, 2, 3];
$squares = array_map(fn($x) => $x * $x, $numbers);
print_r($squares); // 1, 4, 9
$evens = array_filter($numbers, fn($x) => $x % 2 == 0);
print_r($evens); // 2
Questions and answers:
Clink on Option to Answer
1. What are anonymous (or closures)?
- a) Functions without a name
- b) Functions without body
2. Correct definition for closure:
- a) $f = function($x) {};
- b) $f = function($x) {}
3. How do you define closures inside callback functions?
- a) function($x) => $x + 1
- b) fn($x) => $x + 1