Skip to content

Typed methods

Greg Bowler edited this page May 4, 2026 · 1 revision

Once a class implements get(), the NullableTypeSafeGetter trait provides the rest of the public API.

get()

public function get(string $name):mixed;

This is the raw lookup method. It returns whatever the underlying store contains, or null when the key is missing.

The trait uses this method internally for all typed lookups.

Scalar getters

These methods cast non-null values using PHP's normal scalar casting rules:

  • getString(string $name): ?string
  • getInt(string $name): ?int
  • getFloat(string $name): ?float
  • getBool(string $name): ?bool

Example:

$store = new KeyValueStore([
	"intString" => "105",
	"price" => "19.99",
	"enabled" => "1",
]);

echo $store->getInt("intString");
echo $store->getFloat("price");
var_dump($store->getBool("enabled"));

If the key is missing, each method returns null.

getDateTime()

public function getDateTime(string $name): ?DateTimeInterface;

This method handles three cases:

  • if the stored value is already a DateTimeInterface, it is returned as-is
  • if the stored value is numeric, it is treated as a Unix timestamp
  • otherwise the value is passed to DateTimeImmutable

Example:

$store = new KeyValueStore([
	"published" => 1714550400,
]);

echo $store->getDateTime("published")?->format("Y-m-d");

getInstance()

public function getInstance(string $name, string $className);

Use this when the stored value should already be an object instance.

$store = new KeyValueStore([
	"date" => new DateTimeImmutable("2024-05-01"),
]);

$date = $store->getInstance("date", DateTimeInterface::class);

If the key is missing, null is returned.

If the value exists but is not an instance of the requested class or interface, a TypeError is thrown.

This is useful when the storage contains mixed values but a particular key is expected to hold one object type.

Choosing between get() and the typed methods

Use get() when:

  • the value is not one of the common built-in scalar or date types
  • you want to handle conversion yourself
  • the value may be an array or another mixed structure

Use the typed methods when:

  • the underlying data source stores strings that need casting
  • you want a consistent null result for missing keys
  • you want the calling code to be explicit about the expected type

Finally, see how values from Callbacks can be implemented.

Clone this wiki locally