Set
The Set
class is a generic, type-safe implementation of a unique-value collection in PHP. It prevents duplicate values and maintains the order of insertion.
Purpose
This class provides a way to manage a set of unique items. It works similarly to JavaScript's Set
object, offering operations like add
, has
, delete
, and clear
, while also ensuring type safety using PHPDoc generics.
Template Support
The class is declared with a generic template @template T
, allowing you to enforce type consistency for the stored items. For example, a Set<string>
will only accept string values.
Methods
-
add(T $value): void
Adds a value to the set if it does not already exist. -
has(T $value): bool
Checks if the set contains the given value. -
delete(T $value): void
Removes the specified value from the set. -
clear(): void
Removes all values from the set. -
values(): T[]
Returns an array of all values in the set, preserving insertion order. -
size(): int
Returns the total number of values in the set.
Key Generation Logic
Internally, the class generates a unique key for each value to ensure uniqueness:
- Object: Uses
spl_object_id
to track unique instances. - Array: Uses
md5(serialize($value))
to create a hash key. - Scalar: The scalar value itself is used as the key.
Example Usage
<?php
use Lib\Set;
$set = new Set();
$set->add('apple');
$set->add('banana');
$set->add('apple'); // Duplicate, won't be added
echo $set->has('banana') ? 'Yes' : 'No'; // Yes
echo $set->size(); // 2
$set->delete('banana');
print_r($set->values());
?>
For implementation details, refer to the file: src/Lib/Set.php
.