Memos - PHP tips

CALLABLE

function printFormatted(callable $format, $str) {
  echo $format($str);
  echo "<br>";
}

function exclaim($str) { return $str . "!"; }
printFormatted("exclaim", "Hello World");

FN : ARROW FUNCTIONS

The fn keyword is used to create arrow functions. Arrow functions are only available in PHP versions 7.4 and up. Arrow functions have access to all variables from the scope in which they were created. The general syntax of an arrow function is:

fn(arguments) => expression to be returned;

$str = "Hello World";
$my_function = fn($a) => $str . $a;
echo $my_function("!");

EMPTY

empty() keyword acts as a function which returns true if a variable does not exist, or if its value is considered empty. The empty keyword also evaluates expressions which are not in a variable.

A value is considered empty if its value is any of the following:

An empty string An empty array The integer 0 The floating point number 0.0 The string "0" Boolean false null

LIST

Assign elements of an array to variables. If there are not enough elements in the array it will output a notice and assign null to the remaining variables. Choose which element are assigned to the variables can be selected using arrow => syntax.

list($a, $b, $c) = [1, 2, 3];
list(2 => $a, 0 => $b, 1 => $c) = [1, 2, 3];

XOR

if(5 < 3 xor 5 < 10) {
  echo "Only one of the expressions was true";
}

YIELD FROM

Use yield from to create a generator function:

function countTo4() {
  yield from [1, 2, 3];
  yield 4;
}

FUNCTIONS ARGUMENTS

...

Variable Number of Arguments By using the ... operator in front of the function parameter, the function accepts an unknown number of arguments. This is also called a variadic function.

The variadic function argument becomes an array.

function myFamily($lastname, ...$firstname) {
    $len = count($firstname);
    for($i = 0; $i < $len; $i++) {
      // code
    }
    return $txt;
  }
  
function total_intervals($unit, DateInterval ...$intervals) {}

passing variadic arguments to another function

function bar($prefix, ...$args) {
    foreach($args as $arg)
      echo "bar: $prefix: $arg\n";
  }
  function foo($prefix, ...$args) {
    echo "Just passing through...\n";
    foreach($args as $arg)
      echo "foo: $prefix: $arg\n";
    bar($prefix, ...$args);
  }
  
  foo("Idefix", "FOO", "BAR");
  bar("Obelix", "ABC", "DEF");

Output:

Just passing through... foo: Idefix: FOO foo: Idefix: BAR bar: Idefix: FOO bar: Idefix: BAR bar: Obelix: ABC bar: Obelix: DEF

Objects as default function argumnts

Utilisation d objets comme valeurs par défaut (à partir de PHP 8.1.0)

function makecoffee($coffeeMaker = new DefaultCoffeeMaker)
{
    return $coffeeMaker->brew();
}

Named arguments

// Utilisant les arguments positionnels :
array_fill(0, 100, 50);

// Utilisant les arguments nommés :
array_fill(start_index: 0, count: 100, value: 50);

DECORATOR

https://refactoring.guru/design-patterns/decorator/php/example