jerodev's avatar

Test if string is property of object with PHPStan

I have a function that takes a key and value to set a property on an object. Like below.

public function setValue(string $key, string $value): void
{
		// Some extra logic

		$this->privateObject->{$key} = $value;
}

I want to be able to enforce that $key is an existing property of a class preferably using PHPStan. I tried using key-of<PrivateObject>, but this does not seem to work with objects.

Currently, I'm manually adding the properties to this function using @phpstan-param 'foo'|"bar"|'baz' $key, but that's so tedious if the object changes.

Does anyone know if this is possible?

0 likes
3 replies
jerodev's avatar

I know the property_exists function, but I don't want to add this check to my code. I would like to have the check done by a static analyzer beforehand.

oakydev's avatar

Afaik you can do $this->privateObject->$key = $value;

Please or to participate in this conversation.