无法解决'Invalid arguments passed'



为什么会出现此错误?

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

索引.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);
        }
    }
?>

addHobby()方法中,必须使用 $this->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);
        }
    }
?>

变量访问是错误的。

<?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.
    }
}
?>

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

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

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

相关内容

最新更新