phpstan: Don't complain about undefined property fetch if __set exists
Given:
class A {
/** @var string[] */
private $data = [];
public function __get(string $var) : ?string {
return $this->data[$var] ?? null;
}
public function __set(string $var, string $value) {
$this->data[$var] = $value;
}
}
$a = new A();
$a->foo = "bar";
echo $a->foo;
Expected: No errors
Actual:
------ ------------------------------------------
17 Access to an undefined property A::$foo.
------ ------------------------------------------
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Comments: 19 (15 by maintainers)
This is a pattern we use at Vimeo a lot:
And I imagine it’s used elsewhere too. Requiring
@propertyannotations to preventAccess to protected property A::$fooerrors seems slightly backwards, as PHP doesn’t have any problem running the code.You can make it the right way and tell PHPStan which magic properties exist and which do not with an extension. If you don’t want to bother with this, you can use ignoreErrors key or universalObjectCrateClasses. There’s plenty of solutions, but saying that anything with __set defines every prioperty is wrong and would make PHPStan less useful.
On Fri, 5 Jan 2018 at 21:09, Ilija Tovilo notifications@github.com wrote:
–
Ondřej Mirtes
@muglug You cannot find out which properties are valid and which aren’t unless you actually run the code.
__getand__setcouldpreg_matchthe name of the property and only allow it in certain situations.FWIW you can also always create your own reflection class and just allow all properties if your class implements the
__getand__setmethods. This has several disadvantages though:__setmethod could only allow the propertybarand throw in all other instancesIMHO you should avoid using the
__getand__setmethods whenever possible. Why not just expose an array?