|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2016-01-27 11:52 UTC] rowan dot collins at gmail dot com
[2016-01-27 14:43 UTC] iletaitunefoisfenghuang at gmail dot com
[2016-02-01 06:26 UTC] stas@php.net
-Package: PHP Language Specification
+Package: *General Issues
[2017-08-04 23:57 UTC] stas@php.net
-Status: Open
+Status: Suspended
[2017-08-04 23:57 UTC] stas@php.net
|
|||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sat Oct 25 13:00:01 2025 UTC |
Description: ------------ An example worth a thousand words : Let's say we have a TableProxy class, with a custom __construct that do stuff around an inner protected static $columns. We want to create an anonymous class based on the abstract class tableProxy, with computed columns, for a fast and dummy script. We cannot do that because : - We cannot override the ctor with a different prototype to pass our external variable - We cannot set the variable after the creation of the anonymous class because we must use the "new" keyword therefore an instance of the anonymous class is created and so the constructor is triggered. Plus if the variable is not public, we have to define a setter in the anonymous class. The only way we can do this, is by creating a first anonymous class : $table = new class($fileBodyName) extends TableProxy {}; Then use reflection on that very anonymous class to set it up without ctor, and then call it manually : $r = new \ReflectionClass($table); $t2 = $r->newInstanceWithoutConstructor(); $t2::$columns = $computedColumns; $t2->__construct($param); So, as we see, there is a way. However we can all admit it's not the easiest way ever. What if we enhance the anonymous class feature to be able to use external variables with inner properties : $anon = new class() use($yolo) extends TableProxy { private $name = $yolo; }; It would be more efficient and save a lot of time. One could say "you just have to think about your definition of your primary class" . Yes, maybe, however I think the intent of anynomous classes is also to allow some freedom, to do stuff that is not inside the drawn lines. What do you think of it, does it worth a RFC or do I miss something and my proposal does not make sense ?