为什么我会收到此错误?
警告: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);
}
}
?>
答案 0 :(得分:2)
在 sudo apt-get install mysql-server
方法中,您必须使用addHobby()
代替$this->hobbies
。最好使用空数组初始化$hobbies
以防止错误。
hobbies
答案 1 :(得分:0)
变量访问错误。
<?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.
}
}
?>
答案 2 :(得分:0)
每次调用addHobby($ hobby)函数时,您的代码都在创建一个新数组,您需要做的就是正确访问它。改变
public function addHobby($hobby) {
$hobbies[] = $hobby;
}
到
public function addHobby($hobby) {
$this->hobbies[] = $hobby;
}