【问题标题】:Can't solve 'Invalid arguments passed'无法解决“传递的参数无效”
【发布时间】:2017-06-10 11:31:03
【问题描述】:

为什么会出现这个错误?

警告:implode():在第 17 行的 /Applications/XAMPP/xamppfiles/htdocs/basis/php/php.php 中传递的参数无效

index.php:

<?php


require_once 'php.php';
$piet = new Persoon();
$piet->voornaam = 'Piet';
$piet->achternaam = 'Jansen';
echo "De naam is: " . $piet->showNaam();

$piet->addHobby('zeilen');
$piet->addHobby('hardlopen');
echo "<br/> De hobbies van {$piet->showNaam()} zijn: {$piet->showHobbies()}";

?>

php.php

<?php
    class Persoon {
        public $voornaam = '';
        public $achternaam = '';
        protected $adres;
        protected $hobbies;

        public function showNaam() {
            return $this->voornaam . ' ' . $this->achternaam;
        }

        public function addHobby($hobby) {
            $hobbies[] = $hobby;
        }

        public function showHobbies() {
            echo implode(', ', $this->hobbies);
        }
    }

?>

【问题讨论】:

  • implode 第二个参数应该是数组所以改变这一行 $this->hobbies[] = $hobby;

标签: php


【解决方案1】:

addHobby() 方法中,您必须使用$this-&gt;hobbies 而不是$hobbies。最好用空数组初始化hobbies,防止出错。

<?php
    class Persoon {
        public $voornaam = '';
        public $achternaam = '';
        protected $adres;
        protected $hobbies = array();

        public function showNaam() {
            return $this->voornaam . ' ' . $this->achternaam;
        }

        public function addHobby($hobby) {
            $this->hobbies[] = $hobby;
        }

        public function showHobbies() {
            echo implode(', ', $this->hobbies);
        }
    }

?>

【讨论】:

    【解决方案2】:

    变量访问是错误的。

    <?php
    class Persoon {
        public $voornaam = '';
        public $achternaam = '';
        protected $adres;
        protected $hobbies;
    
        public function showNaam() {
            return $this->voornaam . ' ' . $this->achternaam;
        }
    
        public function addHobby($hobby) {
            $this->hobbies[] = $hobby; <--- change this
        }
    
        public function showHobbies() {
            //echo implode(', ', $this->hobbies);// remove this
            echo count($this->hobbies) ? implode(', ', $this->hobbies) : "";// this will avoid errors in future if your array is empty.
        }
    }
    
    ?>
    

    【讨论】:

      【解决方案3】:

      每次调用 addHobby($hobby) 函数时,您的代码都会创建一个新数组,您需要做的是正确访问它。改变

      public function addHobby($hobby) {
                  $hobbies[] = $hobby;
              }
      

       public function addHobby($hobby) {
                  $this->hobbies[] = $hobby;
      
              }
      

      【讨论】:

        猜你喜欢
        • 2013-08-06
        • 1970-01-01
        • 1970-01-01
        • 2013-02-28
        • 1970-01-01
        • 2019-09-18
        • 1970-01-01
        • 2014-07-30
        相关资源
        最近更新 更多