-
-
Notifications
You must be signed in to change notification settings - Fork 0
Home
phpgt/propfunc is a very small library with one job: let a PHP class expose methods as if they were normal object properties.
That means we can keep the logic for reading or writing a value in methods such as __propGetName() and __propSetName(), but use the class from the outside like this:
$user->name = "Cody";
echo $user->name;This is especially useful when a value should be:
- read-only
- calculated on demand
- validated before it is stored
- backed by a private property rather than a public one
The library does this through the GT\PropFunc\MagicProp trait, which implements PHP's __get(), __set(), __isset(), and __unset() magic methods.
Note
If you are building with WebEngine, you may not install this package directly very often. It sits underneath other PHP.GT packages, especially phpgt/dom, which WebEngine relies on heavily. In practice, this trait helps those libraries expose DOM-style read-only and computed properties with a familiar API.
use GT\PropFunc\MagicProp;
use DateTimeImmutable;
use DateTimeInterface;
class Day {
use MagicProp;
public function __construct(
private DateTimeInterface $dateTime,
) {}
private function __propGetFuture():bool {
return new DateTimeImmutable() < $this->dateTime;
}
private function __propGetDaysApart():int {
$diff = (new DateTimeImmutable())->diff($this->dateTime);
return $diff->days;
}
}
$day = new Day(new DateTimeImmutable("+3 days"));
echo $day->future ? "Future" : "Past";
echo PHP_EOL;
echo $day->daysApart;The class does not contain public properties called future or daysApart, but the object can still be used as if those properties exist.
Note
Since PHP 8.4, object property hooks were introduced, which will eventually render this library obsolete once dependent libraries drop support for older PHP versions.
To build the smallest useful class with the trait, continue with Getting started.
PHP.GT/PropFunc is a separately maintained component of PHP.GT/WebEngine.