Navigation

Php

How to Handle PHP's Named Arguments

Use PHP 8.0+ named arguments to call functions with parameter names. Improve code readability and skip optional parameters easily.

Table Of Contents

Problem

You need to call functions with many parameters, skip optional ones, or make function calls more readable and self-documenting.

Solution

// Traditional positional arguments
function createUser($name, $email, $age = null, $active = true, $role = 'user') {
    return [
        'name' => $name,
        'email' => $email,
        'age' => $age,
        'active' => $active,
        'role' => $role
    ];
}

// Traditional call (hard to read)
$user = createUser('John', 'john@example.com', null, true, 'admin');

// Named arguments (self-documenting)
$user = createUser(
    name: 'John',
    email: 'john@example.com',
    role: 'admin'
);

// Skip optional parameters
$user = createUser(
    name: 'Alice',
    email: 'alice@example.com',
    age: 25
);

// Arguments in any order
$user = createUser(
    email: 'bob@example.com',
    role: 'moderator',
    name: 'Bob',
    active: false
);

// Array functions with named arguments
$numbers = [3, 1, 4, 1, 5, 9];

// Sort with named arguments
usort($numbers, callback: fn($a, $b) => $a <=> $b);

// Array filter with named arguments
$filtered = array_filter(
    array: $numbers,
    callback: fn($n) => $n > 3
);

// String functions
$text = "Hello World";

// substr with named arguments
$substring = substr(
    string: $text,
    offset: 6,
    length: 5
);

// str_replace with named arguments
$replaced = str_replace(
    search: 'World',
    replace: 'PHP',
    subject: $text
);

// File operations
file_put_contents(
    filename: 'data.txt',
    data: 'Hello, World!',
    flags: FILE_APPEND | LOCK_EX
);

// Database connection
$pdo = new PDO(
    dsn: 'mysql:host=localhost;dbname=app',
    username: 'user',
    password: 'pass',
    options: [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);

// Class constructors with named arguments
class Product {
    public function __construct(
        public string $name,
        public float $price,
        public string $category = 'general',
        public bool $inStock = true,
        public array $tags = []
    ) {}
}

$product = new Product(
    name: 'Laptop',
    price: 999.99,
    category: 'electronics',
    tags: ['computer', 'portable']
);

// Method calls with named arguments
class OrderService {
    public function processOrder(
        string $orderId,
        float $amount,
        string $currency = 'USD',
        bool $sendEmail = true,
        array $metadata = []
    ) {
        // Process order logic
        return "Processed order {$orderId} for {$amount} {$currency}";
    }
}

$service = new OrderService();
$result = $service->processOrder(
    orderId: 'ORD-12345',
    amount: 199.99,
    sendEmail: false,
    metadata: ['source' => 'mobile_app']
);

// API configuration
function configureApi(
    string $baseUrl,
    string $apiKey,
    int $timeout = 30,
    bool $verifySSL = true,
    array $headers = [],
    string $userAgent = 'PHP API Client'
) {
    return [
        'base_url' => $baseUrl,
        'api_key' => $apiKey,
        'timeout' => $timeout,
        'verify_ssl' => $verifySSL,
        'headers' => $headers,
        'user_agent' => $userAgent
    ];
}

$config = configureApi(
    baseUrl: 'https://api.example.com',
    apiKey: 'secret-key',
    timeout: 60,
    headers: ['Accept' => 'application/json']
);

// Email sending function
function sendEmail(
    string $to,
    string $subject,
    string $body,
    string $from = 'noreply@example.com',
    bool $isHtml = false,
    array $attachments = [],
    int $priority = 3
) {
    // Email sending logic
}

sendEmail(
    to: 'user@example.com',
    subject: 'Welcome!',
    body: '<h1>Welcome to our service!</h1>',
    isHtml: true,
    priority: 1
);

// Validation function
function validateData(
    array $data,
    array $rules,
    bool $stopOnFirstFailure = false,
    array $messages = [],
    string $locale = 'en'
) {
    // Validation logic
}

$validation = validateData(
    data: $_POST,
    rules: [
        'email' => 'required|email',
        'password' => 'required|min:8'
    ],
    stopOnFirstFailure: true,
    messages: [
        'email.required' => 'Email is mandatory',
        'password.min' => 'Password too short'
    ]
);

// Mixing positional and named arguments
function processPayment($amount, $currency, $gateway = 'stripe', $metadata = []) {
    return "Processing {$amount} {$currency} via {$gateway}";
}

// Positional first, then named
$result = processPayment(100.00, 'USD', metadata: ['order_id' => '12345']);

// Cache configuration
function setupCache(
    string $driver,
    array $config = [],
    int $ttl = 3600,
    string $prefix = '',
    bool $serialize = true
) {
    return [
        'driver' => $driver,
        'config' => $config,
        'ttl' => $ttl,
        'prefix' => $prefix,
        'serialize' => $serialize
    ];
}

$cache = setupCache(
    driver: 'redis',
    config: ['host' => 'localhost', 'port' => 6379],
    ttl: 7200,
    prefix: 'app:'
);

// Complex function with many parameters
function generateReport(
    string $type,
    DateTime $startDate,
    DateTime $endDate,
    array $filters = [],
    string $format = 'pdf',
    bool $includeCharts = true,
    string $template = 'default',
    array $recipients = [],
    bool $compress = false,
    string $filename = null
) {
    // Report generation logic
}

$report = generateReport(
    type: 'sales',
    startDate: new DateTime('2023-01-01'),
    endDate: new DateTime('2023-12-31'),
    format: 'excel',
    includeCharts: false,
    recipients: ['manager@company.com'],
    filename: 'sales-report-2023.xlsx'
);

// Function with variadic parameters
function logMessage(string $level, string $message, ...$context) {
    $timestamp = date('Y-m-d H:i:s');
    $contextStr = empty($context) ? '' : ' ' . json_encode($context);
    echo "[{$timestamp}] {$level}: {$message}{$contextStr}\n";
}

// Named arguments with variadic
logMessage(
    level: 'ERROR',
    message: 'Database connection failed',
    'host' => 'localhost',
    'port' => 3306,
    'attempts' => 3
);

// Best practices for function design
class UserRepository {
    public function findUsers(
        ?int $limit = null,
        ?int $offset = null,
        ?string $sortBy = null,
        ?string $sortDirection = 'asc',
        ?array $filters = null,
        ?bool $includeDeleted = false
    ): array {
        // Query building logic
        return [];
    }
}

$repository = new UserRepository();
$users = $repository->findUsers(
    limit: 50,
    sortBy: 'created_at',
    sortDirection: 'desc',
    filters: ['status' => 'active']
);

Explanation

Named arguments allow calling functions with parameter names, making code self-documenting and enabling parameter skipping. Use them for functions with many optional parameters.

Position matters only for positional arguments; named arguments can appear in any order. Mix both styles by placing positional arguments first, then named ones.

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Php