PHP.GT

Examples

This page groups together a few small patterns that tend to come up when using MagicProp.

Example 1: expose a private property as read-only

use GT\PropFunc\MagicProp;

class User {
	use MagicProp;

	public function __construct(
		private int $id,
	) {}

	private function __propGetId():int {
		return $this->id;
	}
}

$user = new User(42);
echo $user->id;

This is a good fit for IDs, timestamps, and values initialised in the constructor.

Example 2: validate a writable property

use GT\PropFunc\MagicProp;
use InvalidArgumentException;

class User {
	use MagicProp;

	private string $email = "";

	private function __propGetEmail():string {
		return $this->email;
	}

	private function __propSetEmail(string $email):void {
		$email = trim($email);

		if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
			throw new InvalidArgumentException("Invalid email address");
		}

		$this->email = $email;
	}
}

The caller gets a clean property API, while the class keeps control over validation.

Example 3: expose a calculated property

use GT\PropFunc\MagicProp;

class Name {
	use MagicProp;

	public function __construct(
		private string $first,
		private string $last,
	) {}

	private function __propGetFull():string {
		return "$this->first $this->last";
	}
}

$name = new Name("Ada", "Lovelace");
echo $name->full;

This avoids adding boilerplate methods such as getFull() to the public API when we really want the consumer to think of the value as a property.

Example 4: map one property API to different internal state

use GT\PropFunc\MagicProp;

class Stopwatch {
	use MagicProp;

	private int $startedAt;

	public function __construct() {
		$this->startedAt = time();
	}

	private function __propGetElapsed():int {
		return time() - $this->startedAt;
	}

	private function __propSetElapsed(int $seconds):void {
		$this->startedAt = time() - $seconds;
	}
}

This is the same shape used in the test suite for the age property.

Example 5: optional internal storage

use GT\PropFunc\MagicProp;

class Profile {
	use MagicProp;

	private function __propGetNickname():?string {
		return $this->__prop["nickname"] ?? null;
	}

	private function __propSetNickname(string $nickname):void {
		$this->__prop["nickname"] = $nickname;
	}
}

This can be helpful for optional values that do not need a dedicated declared property.

Example 6: write-once semantics

use GT\PropFunc\MagicProp;
use GT\PropFunc\PropertyReadOnlySetMoreThanOnceException;

class ApiToken {
	use MagicProp;

	private ?string $token = null;

	private function __propGetToken():?string {
		return $this->token;
	}

	private function __propSetToken(string $token):void {
		if($this->token !== null) {
			throw new PropertyReadOnlySetMoreThanOnceException("token");
		}

		$this->token = $token;
	}
}

This exception type is optional, but it can make the intent clearer than a generic runtime exception.