Allow dynamic property creation in macroable classes #47337
Replies: 2 comments 5 replies
-
This is definitely an issue. We're seeing this in some third party packages. Our deprecation log channel was not happy. But, I wouldn't like to see Arr::macro('some-magic-method', function (Arr $arr, array $array) {
$arr->exists();
.... If the |
Beta Was this translation helpful? Give feedback.
-
If your macro is the only one ever accessing that property, you could also use a static property inside the function. function () {
static $property;
return $property ??='something heavy';
} Be aware that this is globally though. Not a big fan of using __get and __set as a solution as that would break potentially a lot of stuff as Laravel is leaning on them a lot. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I don’t know how common this is overall, but I personally have several macros that add additional dynamic properties on the class instance the macro is called on, and I imagine others probably do as well.
Up until PHP 8.1, that worked fine, but dynamic creation of class properties is deprecated as of PHP 8.2 and will result in a fatal error from PHP 9.0.
I would think that anything that’s macroable should still be allowed to create dynamic properties, so I would update the
Macroable
trait accordingly. Unfortunately, the easiest solution, to add theAllowDynamicProperties
attribute, won’t work since that can’t be applied to traits, but explicitly defining a__set()
method works:(In my testing, the
__set()
method always seems to be inherited fromIlluminate\Container\Container::__set()
– can this be relied upon?)Edit:
Nope, some further testing shows that the parent cannot always be relied upon; in some macros, the current class scope has no parent. That makes this more difficult.
Beta Was this translation helpful? Give feedback.
All reactions