0
0
PHPprogramming~5 mins

DNF types (Disjunctive Normal Form) in PHP

Choose your learning style9 modes available
Introduction

DNF types help you write clear and simple rules that combine options with OR and AND. This makes your code easier to understand and check.

When you want to accept multiple different groups of values in a function.
When you need to check if data matches one of several complex conditions.
When you want to simplify complicated if-else checks into clear logical groups.
Syntax
PHP
<?php
// Example of DNF type using union types
function checkValue(int|string $value): bool {
    return is_int($value) || is_string($value);
}
?>

PHP 8.1+ supports union types using the | symbol.

DNF means combining OR (|) and AND (&) types to express complex rules.

Examples
This function accepts either an int or a string.
PHP
<?php
function example1(int|string $x): void {
    echo $x;
}
?>
This shows a DNF type: either a Traversable that is Countable, or a string.
PHP
<?php
function example2((Traversable&Countable)|string $x): void {
    // $x must be Traversable and Countable, or string
}
?>
Sample Program

This program processes an array with numbers and text, showing how to handle different types clearly.

PHP
<?php
// Function processing arrays containing ints or strings
function processData(array $data): string {
    foreach ($data as $item) {
        if (is_int($item)) {
            echo "Number: $item\n";
        } elseif (is_string($item)) {
            echo "Text: $item\n";
        } else {
            echo "Unknown type\n";
        }
    }
    return "Done";
}

$input = [10, "hello", 42, "world"];
$result = processData($input);
echo $result;
?>
OutputSuccess
Important Notes

DNF types combine union (|) and intersection (&) types to express complex type rules.

PHP 8.1+ supports union and intersection types, enabling DNF style type declarations.

Use DNF types to make your function inputs more flexible and your code easier to read.

Summary

DNF types let you combine OR and AND conditions in type declarations.

They help write clear rules for what types a function accepts.

PHP 8.1+ supports these with union (|) and intersection (&) types.