Soccerlife
Soccerlife

Reputation: 751

Can't solve 'Invalid arguments passed'

Why do I get this error?

Warning: implode(): Invalid arguments passed in /Applications/XAMPP/xamppfiles/htdocs/basis/php/php.php on line 17

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

?>

Upvotes: 0

Views: 45

Answers (3)

Rahul
Rahul

Reputation: 2474

Your code is creating a new array everytime you call addHobby($hobby) function , what you need to do is to access it correctly . Change

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

to

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

        }

Upvotes: 0

Niranjan N Raju
Niranjan N Raju

Reputation: 11987

Variable access is wrong.

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

?>

Upvotes: 0

Mohammad Hamedani
Mohammad Hamedani

Reputation: 3354

In addHobby() method, you must be used $this->hobbies instead of $hobbies. It's better to initialize hobbies with empty array to prevent error.

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

?>

Upvotes: 2

Related Questions