works:programmer:php:php-getter-setter
Красивые функциональные Getter и Setter в PHP
Как по мне, идеальный способ сделать Getter и Setter
- test.php
<?php declare(strict_types=1); class Test { function __construct ( private readonly int $id, public int $value, ) { # Nothing more } function id() { return $this->id; } function value(?int $value=null): int { if (is_null($value)) { return $this->value; } return $this->value = $value; } } $test = new Test(42, 255); echo $test->id() . " = " . $test->value() . "\n"; # 42 = 255 get echo $test->id() . " = " . $test->value(44) . "\n"; # 42 = 44 set+get echo $test->id() . " = " . $test->value() . "\n"; # 42 = 44 get
works/programmer/php/php-getter-setter.txt · Последнее изменение: 2024/10/31 01:55 — tuxapuk