我正在PhpStorm中编写一些面向对象的PHP代码,遇到了一个问题。
我看到您需要定义这些PHPDoc注释,我也在尝试这样做。QuestionList
是我的"活动"类,MySQLAdapter
是我的另一个处理数据库和SQL查询的类。
我试图将构造函数$sql_adapter
参数定义为MySQLAdapter
,这样当我点击Ctrl+Space时,我可以看到我的对象的可用函数,但没有任何运气。
第一次使用connect()
方法时,IDE将自动完成方法名称,但在我将sql
字段初始化为$sql_adapter
后,IDE将无法识别$sql
对象的方法。
问题是什么,我目前没有使用PHPDoc吗?
/**
* @param QuestionList MySQLAdapter $sql_adapter
*/
public function __construct($sql_adapter){
$this->questions = array();
$this->sql = new MySQLAdapter();
/* autocompletes this one */
$this->sql->connect();
$this->sql = $sql_adapter;
/* won't autocomplete this one */
$this->sql->connect();
}
@param QuestionList MySQLAdapter $sql_adapter
是一个无意义的类型提示。它试图通过对$sql_adapter
的解释来告诉IDE MySQLAdapter
是QuestionList
类型。这显然毫无意义。注释必须为:
@param MySQLAdapter $sql_adapter
更好的是,使用PHP的类型提示:
public function __construct(MySQLAdapter $sql_adapter) ..
是的,您可以使用PHPDocs使其正常工作。
例如,对象成员$sql
应该声明并记录在类中:
<?php
class Test {
/**
* @var MySQLAdapater
*/
private $sql;
/**
* @param MySQLAdapter $sqlAdapter [description]
*/
public function __construct(MySQLAdapter $sqlAdapter) {
$sqlAdapter; // …is recognized as type MySQLAdapter through @param doc-comment
$this->sql; // …is recognized as type MySQLAdapter through @var doc-comment
}
}
现在IDE将CCD_ 14的任何使用识别为类型CCD_。
根据@ashnazg的评论更新的示例。