Skip to content

Instantly share code, notes, and snippets.

@D1360-64RC14
Last active June 13, 2025 16:19
Show Gist options
  • Select an option

  • Save D1360-64RC14/229b186f621bdbc06c3726288353ebd9 to your computer and use it in GitHub Desktop.

Select an option

Save D1360-64RC14/229b186f621bdbc06c3726288353ebd9 to your computer and use it in GitHub Desktop.
Example of how easy can be creating memoizeble/lazy-initializable attributes using PHP 8.4's property Hooks.
<?php
function LOGOP($value, ?string $identifier = null)
{
echo 'LOGOP';
echo $identifier ? "($identifier)" : '';
echo ': ' . (string) $value . "\n";
return $value;
}
class User
{
public string $uppercaseName {
get => $this->uppercaseName
?? $this->uppercaseName = LOGOP(strtoupper($this->name), 'runned strtoupper');
}
public string $lowercaseName {
get => $this->lowercaseName
?? $this->lowercaseName = LOGOP(strtolower($this->name), 'runned strtolower');
}
public int $age {
get => $this->age
?? $this->age = LOGOP($this->expensiveAgeComputation(), 'runned expensiveAgeComputation');
}
public readonly string $name;
public readonly \DateTime $birth;
public function __construct(string $name, \DateTime $birth)
{
$this->name = $name;
$this->birth = $birth;
}
private function expensiveAgeComputation(): int
{
$yearAge = abs(date('Y') - $this->birth->format('Y'));
if (date('m') - $this->birth->format('m') < 0) {
$yearAge--;
}
return $yearAge;
}
}
$user = new User("Diego", new \DateTime('2003-06-05'));
var_dump($user->uppercaseName);
var_dump($user->uppercaseName);
var_dump($user->uppercaseName);
var_dump($user->lowercaseName);
var_dump($user->lowercaseName);
var_dump($user->lowercaseName);
var_dump($user->age);
var_dump($user->age);
var_dump($user->age);
LOGOP(runned strtoupper): DIEGO
string(5) "DIEGO"
string(5) "DIEGO"
string(5) "DIEGO"
LOGOP(runned strtolower): diego
string(5) "diego"
string(5) "diego"
string(5) "diego"
LOGOP(runned expensiveAgeComputation): 22
int(22)
int(22)
int(22)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment