note 128858 added to reflectionproperty.setvalue

From: Date: Tue, 05 Sep 2023 14:35:25 +0000
Subject: note 128858 added to reflectionproperty.setvalue
Groups: php.notes 
Request: Send a blank email to php-notes+get-220819@lists.php.net to get a copy of this message
An super simple example on how to automatically fill private properties of an Entity with given "database" data: <?php interface Entity {} class User implements Entity { private int $id; private string $username; public function __toString(): string { return $this->id . ': '. $this->username; } } $dbData = [ 'id' => 1, 'username' => 'PhpUser123' ]; function fillEntity(Entity $entity, array $dbData): void { $reflectionClass = new ReflectionClass($entity); foreach ($reflectionClass->getProperties() as $reflectionProp) { $propName = $reflectionProp->getName(); if(!array_key_exists($propName, $dbData)) { continue; } $reflectionProp->setValue($entity, $dbData[$propName]); } } $user = new User; fillEntity($user, $dbData); echo $user; ---- Server IP: 45.112.84.4 Probable Submitter: 45.91.157.134 (proxied: 2a02:3038:6e0:653a:b18c:7f02:b20a:505c) ---- Manual Page -- https://php.net/manual/en/reflectionproperty.setvalue.php Edit -- https://main.php.net/note/edit/128858 Del: integrated -- https://main.php.net/note/delete/128858/integrated Del: useless -- https://main.php.net/note/delete/128858/useless Del: bad code -- https://main.php.net/note/delete/128858/bad+code Del: spam -- https://main.php.net/note/delete/128858/spam Del: non-english -- https://main.php.net/note/delete/128858/non-english Del: in docs -- https://main.php.net/note/delete/128858/in+docs Del: other reasons-- https://main.php.net/note/delete/128858 Reject -- https://main.php.net/note/reject/128858 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#220819) next »