Last active
November 15, 2021 19:02
-
-
Save JasonTheAdams/a90bdb2492ceaab094222333c37d4f6b to your computer and use it in GitHub Desktop.
A backwards-compatible trait for deprecated dynamic properties in 8.2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* This is a very simple and basic trait for overcoming the deprectation of dynamic properties in 8.2, and broken in 9.0. | |
* | |
* If using a 8.2 or later, use the #[AllowDynamicProperties] attribute instead of this. | |
* | |
* I suggest this is better than traditional dynamic properties for the simple fact that it's excplicit and therefore | |
* intentional. If your class already has magic methods then you don't need this. This will work in 8.2 or later and as far | |
* back as 5.4, so it should cover most sensible cases. | |
* | |
* @see https://wiki.php.net/rfc/deprecate_dynamic_properties | |
*/ | |
Trait DynamicProperties { | |
private $dynamicProperties = []; | |
public __get($prop) { | |
return $this->dynamicProperties[$prop]; | |
} | |
public __set($prop, value) { | |
$this->dynamicProperties[$prop] = $value; | |
} | |
public __isset($prop) { | |
return isset($this->dynamicProperties[$prop]); | |
} | |
public __unset($prop) { | |
unset($this->dynamicProperties[$prop]); | |
} | |
} | |
// Usage | |
class MyClassThatAllowsDynamicProperties { | |
use DynamicProperties; | |
// do other stuff | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment