Skip to content

Type safe getters

Greg Bowler edited this page Apr 23, 2026 · 1 revision

Session and SessionStore both implement Gt\TypeSafeGetter\TypeSafeGetter.

That gives us a consistent way to read common types without manually casting every value. The same getter style is used across several PHP.GT libraries.

Available getters

  • get(string $name):mixed
  • getString(string $name):?string
  • getInt(string $name):?int
  • getFloat(string $name):?float
  • getBool(string $name):?bool
  • getDateTime(string $name):?DateTimeInterface
  • getInstance(string $name, string $className)

Reading scalar values

$session->set("auth.userId", "42");
$session->set("basket.total", "12.50");
$session->set("ui.compact", "1");

$userId = $session->getInt("auth.userId");
$total = $session->getFloat("basket.total");
$compact = $session->getBool("ui.compact");

If the value is missing, the typed getter returns null.

If the value exists, scalar getters cast to the requested PHP type.

Reading date and time values

getDateTime() accepts values that can be turned into a DateTimeImmutable.

$session->set("auth.lastSeen", "2026-04-23 10:15:00");

$lastSeen = $session->getDateTime("auth.lastSeen");
echo $lastSeen?->format("j F Y");

Numeric values are treated as Unix timestamps.

Reading objects

getInstance() checks that a stored object is an instance of the class or interface we ask for.

$basket = $session->getInstance("checkout.basket", Basket::class);

If the stored value is the wrong object type, a TypeError is thrown. This is intentional: it catches session-shape mistakes close to where they are read.

Use typed getters at boundaries

It is usually best to use typed getters as soon as session data enters application logic:

function do_save(Session $session, ProfileRepository $profiles):void {
	$userId = $session->getInt("auth.userId");

	if(!$userId) {
		throw new RuntimeException("You must be signed in to save a profile.");
	}

	$profiles->saveForUser($userId);
}

That keeps the rest of the function working with known types.


Next, look at the browser cookie and PHP options in Session cookies and configuration.

Clone this wiki locally