【问题标题】:How can I pass a parameter to a function which isn't declared yet?如何将参数传递给尚未声明的函数?
【发布时间】:2017-10-24 06:46:17
【问题描述】:

这是我的代码:

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() 函数中的循环中的值。无论如何,有什么解决办法吗?

【问题讨论】:

  • 你想达到什么目的? investigate_words 逻辑上应该怎么做?

标签: php function parameter-passing


【解决方案1】:

在这种情况下,我们可以使用Closure。条件参数可以是可调用的。

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;
    }
}

【讨论】:

  • 我不知道它是否有效(我现在无法访问计算机来测试它,我稍后会这样做),但它似乎是正确的.谢谢,点赞
猜你喜欢
  • 1970-01-01
  • 2016-09-30
  • 1970-01-01
  • 2016-12-20
  • 2022-01-10
  • 2016-07-19
  • 1970-01-01
  • 2023-03-17
  • 2015-10-30
相关资源
最近更新 更多