PHP 8 introdujo dos mejoras de sintaxis que hacen el código más legible y robusto: los named arguments permiten llamar a funciones especificando el nombre del parámetro en lugar de su posición, y los union types permiten declarar que un valor puede ser de más de un tipo, con verificación real en tiempo de ejecución.
Named arguments: llamar por nombre de parámetro
<?php
// Sin named arguments: hay que recordar el orden
$resultado = array_slice([1, 2, 3, 4, 5], 1, 3, true);
// Con named arguments: orden independiente, más legible
$resultado = array_slice(
array: [1, 2, 3, 4, 5],
offset: 1,
length: 3,
preserve_keys: true,
);
// [1 => 2, 2 => 3, 3 => 4]
// Especialmente útil con funciones con muchos parámetros opcionales
$imagen = imagecreatetruecolor(width: 800, height: 600);
?>
Named arguments en tus propias funciones
<?php
function crearUsuario(
string $nombre,
string $email,
string $rol = 'lector',
bool $activo = true,
int $maxItems = 25,
): array {
return compact('nombre', 'email', 'rol', 'activo', 'maxItems');
}
// Solo pasas los parámetros que necesitas cambiar
$admin = crearUsuario(
nombre: 'Ana García',
email: '[email protected]',
rol: 'admin',
// activo y maxItems toman sus valores por defecto
);
$inactivo = crearUsuario(
nombre: 'Bot',
email: '[email protected]',
activo: false,
);
print_r($admin);
?>
Union types: múltiples tipos aceptados
<?php
// Una función que acepta string o int como identificador
function buscarProducto(string|int $id): array
{
if (is_string($id)) {
// buscar por slug
return ['tipo' => 'slug', 'valor' => $id];
}
// buscar por id numérico
return ['tipo' => 'id', 'valor' => $id];
}
$p1 = buscarProducto(42);
$p2 = buscarProducto('teclado-mecanico');
// buscarProducto(3.14); // TypeError: float no es string ni int
?>
Union types con null
<?php
// ?string es equivalente a string|null
function formatearFecha(string|null $fecha): string
{
if ($fecha === null) {
return 'Fecha no disponible';
}
return date('d/m/Y', strtotime($fecha));
}
// Tipo de retorno con unión
function encontrarUsuario(int $id): object|null
{
// devuelve un objeto o null si no existe
return null;
}
?>
Los tipos mixed y never
<?php
// mixed: acepta cualquier tipo (incluido null)
function registrar(mixed $valor): void
{
file_put_contents('/tmp/log.txt', print_r($valor, true) . "n", FILE_APPEND);
}
registrar('texto');
registrar(42);
registrar(['array', 'de', 'datos']);
registrar(null);
// never: el tipo de retorno de funciones que nunca retornan
function redirigir(string $url): never
{
header("Location: $url");
exit;
}
function lanzarError(string $mensaje): never
{
throw new RuntimeException($mensaje);
}
?>
Named arguments combinados con spread operator
<?php
function punto3D(float $x, float $y, float $z = 0.0): string
{
return "({$x}, {$y}, {$z})";
}
$coordenadas = ['y' => 2.0, 'x' => 1.0]; // orden diferente al de la función
echo punto3D(...$coordenadas, z: 3.0);
// (1.0, 2.0, 3.0)
?>
La documentación oficial de named arguments y la de declaraciones de tipos detallan las restricciones de uso con funciones internas, atributos y tipos de intersección introducidos en PHP 8.1.
