Skip to main content

Shared Methods

Every UUID class (UuidV1 through UuidV8) implements the same UuidInterface and uses the same UuidMethodsTrait. That means these methods behave identically no matter which version you're working with — only generate() differs between versions.

fromString(string $uuid): static

Wraps an existing UUID string in the matching class. The string must already be a valid UUID for that specific version, or an InvalidArgumentException is thrown.

use DomainFlow\Uuid\UuidV4;

$uuid = UuidV4::fromString('f47ac10b-58cc-4372-a567-0e02b2c3d479');

fromString() does not convert between versions. Passing a UUIDv4 string to UuidV1::fromString() throws, since the version nibble won't match.

isValid(string $uuid): bool

Statically checks whether a string is a valid UUID for that version, without constructing an instance.

UuidV4::isValid('f47ac10b-58cc-4372-a567-0e02b2c3d479'); // true
UuidV4::isValid('not-a-uuid'); // false

equals(UuidInterface $other): bool

Compares two UUID instances by their string value.

$a = UuidV4::generate();
$b = UuidV4::fromString((string) $a);

$a->equals($b); // true

__toString(): string

Every UUID instance can be cast to its canonical, lowercase string form.

echo (string) UuidV4::generate();

jsonSerialize(): string

UUID objects implement PHP's JsonSerializable, so they serialize to their string form automatically when passed to json_encode().

$uuid = UuidV4::generate();

echo json_encode(['id' => $uuid]);
// {"id":"f47ac10b-58cc-4372-a567-0e02b2c3d479"}

fromJson(string $json): static

Creates a UUID from a JSON-encoded string literal (not an object).

$uuid = UuidV4::fromJson('"f47ac10b-58cc-4372-a567-0e02b2c3d479"');

Throws a JsonException if the input isn't valid JSON, or the decoded value isn't a string.


UuidInterface & UuidMethodsTrait

  • UuidInterface is the contract every UUID class implements: fromString(), isValid(), equals(), __toString(), and (via JsonSerializable) jsonSerialize().
  • UuidMethodsTrait provides the shared implementation of equals(), __toString(), jsonSerialize(), fromString(), and fromJson() used by all eight version classes.

Because every version implements the same interface, you can type-hint UuidInterface in your own code and accept any UUID version interchangeably:

use DomainFlow\Uuid\Interface\UuidInterface;

function logId(UuidInterface $id): void
{
echo "Generated: {$id}\n";
}