What does @param mean in a class?

2019-02-11 22:41发布

What does the @param mean when creating a class? As far as I understand it is used to tell the script what kind of datatype the variables are and what kind of value a function returns, is that right? For example:

/**
 * @param string $some
 * @param array $some2
 * @return void
 */

Isn´t there another way to do that, I am thinking of things like: void function() { ... } or something like that. And for variables maybe (int)$test;

标签: php class param
5条回答
看我几分像从前
2楼-- · 2019-02-11 23:00

PHP is entirely oblivious to comments. It is used to describe the parameters the method takes only for making the code more readable and understandable.

Additionally, good code practice dedicates to use certain names (such as @param), for documentation generators.

Some IDEs will include the @param and other information in the tooltip when using a hovering over the relevant method.

查看更多
小情绪 Triste *
3楼-- · 2019-02-11 23:07

@param doesn't have special meaning in PHP, it's typically used within a comment to write up documentation. The example you've provided shows just that.

If you use a documentation tool, it will scour the code for @param, @summary, and other similar values (depending on the sophistication of the tool) to automatically generate well formatted documentation for the code.

查看更多
ら.Afraid
4楼-- · 2019-02-11 23:09

@param is a part of the description comment that tells you what the input parameter type is. It has nothing to do with code syntax. Use a color supported editor like Notepad++ to easily see whats code and whats comments.

查看更多
倾城 Initia
5楼-- · 2019-02-11 23:10

As others have mentioned the @param you are referring to is part of a comment and not syntactically significant. It is simply there to provide hints to a documentation generator. You can find more information on the supported directives and syntax by looking at the PHPDoc project.

Speaking to the second part of your question... As far as I know, there is not a way to specify the return type in PHP. You also can't force the parameters to be of a specific primitive type (string, integer, etc).

You can, however, required that the parameters be either an array, an object, or a specific type of object as of PHP 5.1 or so.

function importArray(array $myArray)
{
}

PHP will throw an error if you try and call this method with anything besides an array.

class MyClass
{
}

function doStuff(MyClass $o)
{
}

If you attempt to call doStuff with an object of any type except MyClass, PHP will again throw an error.

查看更多
啃猪蹄的小仙女
6楼-- · 2019-02-11 23:23

I know this is old but just for reference, the answer to the second part of the question is now, PHP7.

// this function accepts and returns an int
 function age(int $age): int{

  return 18;
}
查看更多
登录 后发表回答