I have an instance of a stdClass with some properties. Which is the correct way to declare those properties in PHPDoc? I tried this, but it seems it's not ok:
/**
* @var $requestParams stdClass
* @property string cancelUrl
*/
$requestParams = $someObj->getSomething();
Given your code example, the best you can do is denote that the $requestParams
is of type stdClass
via @var
. Your use of @property
there won't do anything for you, because that tag is specifically defined only for magic properties that exist on a class... therefore, @property
will only be read and interpreted when it's in a class docblock.
If your only need is to show that $requestParams is an instance of stdClass, then @var is all you need. However, if you further want to denote that $requestParams->cancelUrl is a known string property, without changing to an actual defined class, you'd have to use another local variable in the same way that $requestParams is a local variable:
/** @var stdClass $requestParams */
$requestParams = $someObj->getSomething();
/** @var string $cancelUrl */
$cancelUrl = $requestParams->cancelUrl;
Beyond answering your direct question -- if it's really important to you to show your readers that this $requestParams element has certain defined properties, I would choose to write a formal class for it. The implementation in that class can still just be an internal stdClass for holding values, of course.
The problem with new stdClass()
is that you can declare properties on the fly so it would be hard for any documenter to parse through all your code to find all of the places where you add new properties so instead you need to create a class for it and document that class:
So instead of doing this:
/**
* ... doc block here
*/
class SomeObj {
/**
* ... doc block here
* @return stdClass
*/
function getSomething() {
return new stdClass();
}
}
You do this:
/**
* ... doc block here
*/
class SomeObj {
/**
* ... doc block here
* @return Something
*/
function getSomething() {
return new Something();
}
}
/**
* ... doc block here
*/
class Something {
/**
* @var string
*/
public $cancelUrl;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With