note 130220 added to language.oop5.late-static-bindings

From: Date: Wed, 02 Apr 2025 21:42:13 +0000
Subject: note 130220 added to language.oop5.late-static-bindings
Groups: php.notes 
Request: Send a blank email to php-notes+get-222056@lists.php.net to get a copy of this message
I haven't seen anyone use an anonymous function but it works! This way you only have to add ONE function in your parent class instead of cluttering up your children. It works for regular classes, extended classes, abstract classes, and even classes that inherit interfaces <?php class A { public static string $name = 'A'; public static string $birthday = 'February'; public static string $hairColor = 'Light Brown'; public static function getProperty(string $propertyName) { $property = function ($name): string { return static::$$name; }; return $property($propertyName); } public static function getProperties() { $properties = function () { return get_class_vars(static::class); }; return $properties(); } } class B extends A { public static string $name = 'B'; public static string $birthday = 'February'; public static string $hairColor = 'Blonde'; } // class A echo 'My name is: '.A::getProperty('name')."\n"; print_r(A::getProperties()); echo "\n"; // Class B echo 'My name is: '.B::getProperty('name')."\n"; print_r(B::getProperties()); ?> The result will be: // My name is: A // Array // ( // [name] => A // [birthday] => February // [hairColor] => Light Brown // ) // // My name is: B // Array // ( // [name] => B // [birthday] => February // [hairColor] => Blonde // ) Hopefully this helps someone else that likes simple clean code. ---- Server IP: 45.112.84.4 Probable Submitter: 45.112.84.18 (proxied: 72.250.16.132) ---- Manual Page -- https://php.net/manual/en/language.oop5.late-static-bindings.php Edit -- https://main.php.net/note/edit/130220 Del: integrated -- https://main.php.net/note/delete/130220/integrated Del: useless -- https://main.php.net/note/delete/130220/useless Del: bad code -- https://main.php.net/note/delete/130220/bad+code Del: spam -- https://main.php.net/note/delete/130220/spam Del: non-english -- https://main.php.net/note/delete/130220/non-english Del: in docs -- https://main.php.net/note/delete/130220/in+docs Del: other reasons-- https://main.php.net/note/delete/130220 Reject -- https://main.php.net/note/reject/130220 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#222056) next »