Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare properties of a local variable in PHPDoc

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();
like image 535
johnutzm Avatar asked Jun 12 '13 12:06

johnutzm


2 Answers

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.

like image 52
ashnazg Avatar answered Nov 10 '22 15:11

ashnazg


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;
}
like image 45
chrislondon Avatar answered Nov 10 '22 15:11

chrislondon