且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP将变量强制转换为foreach循环中的对象类型

更新时间:2022-06-03 21:23:40

在Netbeans和IntelliJ中,您可以在注释中使用 @var

In Netbeans and IntelliJ you are able to use @var in a comment:

/* @var $variable ClassName */
$variable->

IDE现在将知道$ variable是ClassName类,并在-> 。

The IDE will now know that $variable is of the class ClassName and hint after the ->.

您也可以在自己的IDE中进行尝试。

You can try it out in your own IDE as well.

您还可以在 getPersonalities()方法中创建 @return 批注,说明返回将是 ClassName [] ,表示ClassName对象的数组:

You can also create a @return annotation in a getPersonalities() method stating that the return will be a ClassName[], which means an array of ClassName objects:

/**
 * Returns a list of Personality objects
 * @return Personality[]
 */
function getPersonalities() {
    return $this->personalities;
}

这还取决于您的IDE如何解释这种类型的提示。

this also depends on how your IDE is interpreting this type of hinting.

要在foreach循环中使用它,您可以执行1:

To use this in foreach loops you can do 1:

/* @var $existing_personality Personality */
foreach( $quiz_object->personalities as $existing_personality ){
}

或2:

foreach( $quiz_object->getPersonalities() as $existing_personality ){
}

如果您的IDE足够好,都应该启用IDE提示。

both should enable IDE hinting, if your IDE is kind enough.

另外,如果您想在自己的类中使用它,可以在声明类变量时使用相同的签名:

As an extra note, if you want to use this inside it's own class, you can use the same signature when declaring a class variable:

class MyClass
{ 

    /** 
    * @var ClassName[] $variable List of ClassName objects. 
    */ 
    var $variable;

}