php PHP在foreach循环中将变量转换为对象类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12409915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP Casting Variable as Object type in foreach Loop
提问by Luke
Within the following code, $quiz_object->personalitiescontains an array of Personalityobjects.
在以下代码中,$quiz_object->personalities包含一个Personality对象数组。
// Loop through each personality that exists for the quiz
foreach($quiz_object->personalities AS $existing_personality)
{
// Show all of the existing personalities
echo $existing_personality->GetQuizMakerPersonalityHTML();
}
How do I "cast" (I think that's the right word) my variable $existing_personalitywithin the foreach loop as the object type?
我如何$existing_personality将 foreach 循环中的变量“转换”(我认为这是正确的词)作为对象类型?
I wish to do this so that when I type $existing_personality->, I get the list of public functions available for that object type.
我希望这样做,以便当我输入时$existing_personality->,我会得到该对象类型可用的公共函数列表。
UPDATE
更新
At the moment, Zend Studio doesn't know I am looping through an array of Personalityobjects within the loop, it just thinks it's a standard variable. However, it is a type and my code works perfectly well. I just want the IDE hints on my variable within the foreach loop.
目前,Zend Studio 不知道我在循环中遍历Personality对象数组,它只是认为它是一个标准变量。但是,它是一种类型,我的代码运行良好。我只想要 IDE 对 foreach 循环中的变量的提示。
Just so that I'm clear, the hints appear for every other object, if I have:
为了让我清楚,提示会出现在每个其他对象上,如果我有:
$personality_object = new Personality();
// I get the IDE hints here
echo $personality_object->MyFunction();
But as soon as I start looping in a foreach, Zend has no way of knowing that I'm looping through an array of Objects.
但是一旦我开始在 foreach 中循环,Zend 就无法知道我正在循环遍历对象数组。
This is how the array of personalities is defined initially within my Personalityobject:
这是在我的Personality对象中最初定义个性数组的方式:
class Personality
{
// Array of Personality objects
public $personalities = array();
}
回答by Krycke
It much depends on the IDE you are using.
这在很大程度上取决于您使用的 IDE。
In Netbeans and IntelliJ you are able to use @varin a comment:
在 Netbeans 和 IntelliJ 中,您可以@var在评论中使用:
/* @var $variable ClassName */
$variable->
The IDE will now know that $variable is of the class ClassName and hint after the ->.
IDE 现在将知道 $variable 属于 ClassName 类,并在->.
You can try it out in your own IDE as well.
您也可以在自己的 IDE 中试用它。
You can also create a @returnannotation in a getPersonalities()method stating that the return will be a ClassName[], which means an array of ClassName objects:
您还可以@return在getPersonalities()方法中创建一个注解,说明返回将是 a ClassName[],这意味着 ClassName 对象的数组:
/**
* Returns a list of Personality objects
* @return Personality[]
*/
function getPersonalities() {
return $this->personalities;
}
this also depends on how your IDE is interpreting this type of hinting.
这也取决于您的 IDE 如何解释这种类型的提示。
To use this in foreach loops you can do 1:
要在 foreach 循环中使用它,您可以执行以下操作:
/* @var $existing_personality Personality */
foreach( $quiz_object->personalities as $existing_personality ){
}
or 2:
或 2:
foreach( $quiz_object->getPersonalities() as $existing_personality ){
}
both should enable IDE hinting, if your IDE is kind enough.
如果您的 IDE 足够友好,两者都应该启用 IDE 提示。
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;
}
回答by lordvig
just thought I'd throw this in there for those using phpStorm.
只是想我会把它扔给那些使用 phpStorm 的人。
I found the way to get the IDE to auto-populate the methods for an object was by including a quick if check beforeheand checking that the object exists and that the $var was an instance of said object.
我发现让 IDE 自动填充对象方法的方法是预先包含快速 if 检查并检查对象是否存在以及 $var 是所述对象的实例。
Example:
例子:
foreach ($objArray as $obj) {
if (is_object($obj) && $obj instanceof DataObject) {
$obj->thisMethodShouldBeAvailableInPHPStormNow();
}
Found this question while searching for a better way, but the above works for me.
在寻找更好的方法时发现了这个问题,但上述方法对我有用。
Cheers!
干杯!
回答by Daniel Guerrero
I know this post is old but I think this may help someone:
我知道这篇文章很旧,但我认为这可能对某人有所帮助:
In PhpStorm works this way, maybe in others too.
在 PhpStorm 中以这种方式工作,也许在其他人中也是如此。
/**
* @param ClassName[] $variables
*/
public function loopFunction($variables){
foreach ($variables as $variable) {
echo $variable->functionName();
}
}
回答by CommaToast
You can always call out to a separate function from within the foreach, and declare the class in the function declaration. This might also have the benefit of letting you reuse this code elsewhere. For example inside the function getPriceFromProductbelow, you see how I declare the class of $product to be Product.
您始终可以从 foreach 中调用单独的函数,并在函数声明中声明类。这也可能有利于让您在其他地方重用此代码。例如,在getPriceFromProduct下面的函数中,您会看到我如何将 $product 类声明为 Product。
Of course I agree it would be nice to not have to do it this way but hey, it works.
当然,我同意不必这样做会很好,但是嘿,它有效。
class ProductBundle {
private $products; //buy this
public function get_products() { return $this->products; }
public function add_product($product) { $this->products[] = $product; }
public function get_price() {
$products = $this->get_products();
$prices = array();
foreach($products as $product) {
$prices[] = $this->getPriceFromProduct($product);
}
return array_sum($prices);
}
private function getPriceFromProduct(Product $product) {
$price = $product->get_price();
return $price;
}
回答by jleeothon
If you want actual type declarations in the code as opposed to comments that could be picked up differently depending on the IDE, you can use the array_*functions, for example array_walk.
如果您想要代码中的实际类型声明,而不是根据 IDE 可能以不同方式获取的注释,您可以使用array_*函数,例如array_walk.
array_walk($quiz_object->personalities, function (Personality $p) {
echo $existing_personality->GetQuizMakerPersonalityHTML();
});

