note 130140 added to class.reflectionproperty

From: Date: Tue, 11 Mar 2025 21:50:27 +0000
Subject: note 130140 added to class.reflectionproperty
Groups: php.notes 
Request: Send a blank email to php-notes+get-221970@lists.php.net to get a copy of this message
There is way to get property type without reflection. Not very clear, but there is: <?php function getPropType(object $object, string $propName): string { try { $object->{$propName} = new class {}; } catch (\TypeError $e) { // @hint: question mark in type can be used to detect if property is nullable if (preg_match('/of type \??(.*)$/', $e->getMessage(), $m)) { return $m[1]; } throw $e; } catch (\Error $e) { // property doesn't exist or is not public throw $e; } throw new \TypeError(sprintf('Property %s of class %s has no type', $propName, $object::class)); // alternatively return 'mixed'; } ?> note: in case you need access to private/protected properties its easy to change this to be embedded in any class: <?php trait PropertyTypeResolver { public function getPropType(string $propName): string { try { $this->{$propName} = new class {}; } catch (\TypeError $e) { // @hint: question mark in type can be used to detect if property is nullable if (preg_match('/of type \??(.*)$/', $e->getMessage(), $m)) { return $m[1]; } throw $e; } catch (\Error $e) { // property doesn't exist throw $e; } throw new \TypeError(sprintf('Property %s of class %s has no type', $propName, $this::class)); // alternatively return 'mixed'; } } ?> ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.5.137 (proxied: 178.219.142.108) ---- Manual Page -- https://php.net/manual/en/class.reflectionproperty.php Edit -- https://main.php.net/note/edit/130140 Del: integrated -- https://main.php.net/note/delete/130140/integrated Del: useless -- https://main.php.net/note/delete/130140/useless Del: bad code -- https://main.php.net/note/delete/130140/bad+code Del: spam -- https://main.php.net/note/delete/130140/spam Del: non-english -- https://main.php.net/note/delete/130140/non-english Del: in docs -- https://main.php.net/note/delete/130140/in+docs Del: other reasons-- https://main.php.net/note/delete/130140 Reject -- https://main.php.net/note/reject/130140 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#221970) next »