Last active
June 13, 2025 16:19
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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