这是我的代码:
class myclass{
public function index(){
$words = ['word1', 'word2', 'word3'];
$result = sizeof($words);
$condition = in_array($word, $words) || strlen($word) <= 3;
$res = $this->investigate_words( $words, $result, $condition )
}
public function investigate_words($words, $result, $condition)
{
foreach($words as $word){
if($condition){
$result--;
}
}
return $result;
}
}
请关注这一行:
$condition = in_array($word, $words) || strlen($word) <= 3;
在这一行中,$word
尚未宣布。它应该是存在于investigate_words()
函数中的循环中的值。无论如何,有什么解决方案我该如何处理?
答案 0 :(得分:1)
在这种情况下我们可以使用Closure
。 condition参数可以是可调用的。
class myclass{
public function index(){
$words = ['word1', 'word2', 'word3'];
$result = sizeof($words);
$res = $this->investigate_words( $words, $result, function($word){
return strlen($word) <= 3;// || in_array($word, $words); You don't need this commented condition word's coming from array
});
}
public function investigate_words($words, $result,callable $condition)
{
foreach($words as $word){
if($condition($word)){
$result--;
}
}
return $result;
}
}