douba4933 2018-04-18 11:45
浏览 29
已采纳

Php foreach返回错误

I came across this problem. I have two object. One is just to create an array with words and the other one is for string actions. I instantiate an object that add words to an array. When I pass this array as an argument in foreach loop I get an error saying "strtolower expects parameter 1 to be string, array given". I spent some time thinking why is that and then I decided to hardcode the array and pass it as an argument in the same foreach loop. To my suprise it worked. I do not know what is happening.

<?php
class Words
{

  private $words = [];

  public  function addWords(...$string)
  {
    $this->words[] = $string;
  }

  public function getWords()
  {
    return $this->words;
  }

}

class StrAction
{

  public function lowerCase($str)
  {
    if (is_array($str)) {

      $array = [];

      foreach ($str as $word) {

        $newWord = strtolower($word);
        $array[] = $newWord;
      }

      return $array ;
    }else{
      return strtolower($str);
    }
      }

}

$wordBank = new Words();
$wordBank->addWords('HELLO', 'Good Morning', 'alright mate');

$array = ['hello', 'good morning', 'alright mate'];

$strAction = new StrAction();
$strAction->lowerCase($wordBank->getWords());

// $strAction->lowerCase($array);




?>
  • 写回答

2条回答 默认 最新

  • dourong8495 2018-04-18 11:51
    关注

    When you define a variadic argument with ... it is considered an array.

    So, your $string in addWords function definition is already array. And doing

    $this->words[] = $string;
    

    you add a subarray to $this->words.

    To avoid this - merge new values to $this->words:

    $this->words = array_merge($this->words, $string);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!