note 126912 added to function.eval

From: Date: Thu, 10 Mar 2022 08:35:56 +0000
Subject: note 126912 added to function.eval
Groups: php.notes 
Request: Send a blank email to php-notes+get-217703@lists.php.net to get a copy of this message
You can use eval() to combine classes/traits dynamically with anonymus classes: <?php function init($trait, $class) { return (trait_exists($trait) && class_exists($class)) ? eval("return new class() extends {$class} { use {$trait}; };") : false; } trait Edit { function hello() { echo 'EDIT: ' . $this->modulename; } } trait Ajax { function hello() { echo 'AJAX: ' . $this->modulename; } } class MyModule { public $modulename = 'My Module'; } class AnotherModule { public $modulename = 'Another Module'; } init('Edit', 'MyModule')->hello(); # 'EDIT: My Module' init('Ajax', 'AnotherModule')->hello(); # 'AJAX: Another Module' ?> ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.5.135 (proxied: 79.172.252.86) ---- Manual Page -- https://php.net/manual/en/function.eval.php Edit -- https://main.php.net/note/edit/126912 Del: integrated -- https://main.php.net/note/delete/126912/integrated Del: useless -- https://main.php.net/note/delete/126912/useless Del: bad code -- https://main.php.net/note/delete/126912/bad+code Del: spam -- https://main.php.net/note/delete/126912/spam Del: non-english -- https://main.php.net/note/delete/126912/non-english Del: in docs -- https://main.php.net/note/delete/126912/in+docs Del: other reasons-- https://main.php.net/note/delete/126912 Reject -- https://main.php.net/note/reject/126912 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#217703) next »