This forum is now read-only. Please use our new forums at discuss.codecademy.com.

Objects in PHP Forum

View Course » View Exercise

338 points
858beaefff96303788a5511094161aac?s=140&d=retro
Submitted by
nachlop
over 2 years ago

whats wrong with my code

<?php
class Dog {
public $numLegs = 4;
public $name;
public function bark (){
return "woof!";
}
public function greet(){
return "hello my name is". $name;
}
public function __construct($name){
$this -> name = $name;
}

   }

   $dog1 = new Dog('barker');
   $dog2 = new Dog ('Amigo');

   echo $dog1 -> greet()


   ?>

0 votes

permalink

The problem is here - you were missing $this-> before $name. Note that after '->' (calling a method or property) you don't use $:
public function greet() {
return "hello my name is". $this->name;
}

Here's an example. Note how the __construct function is used to 'pick up' the property 'name' from the new instance argument...see second last line

<?php
class Dog {
public $numLegs = 4;
public $name;
public function __construct($name) {
$this->name = $name;
}
public function bark() {
return "Woof";
}
public function greet() {
return "my name is " . $this->name;
}
}
$dog1 = new Dog("Barker");
$dog2 = new Dog("Spot");
echo $dog1->greet() . "";
echo $dog2->name . " says " . $dog2->bark();
?>

134 points
10622d072c3aaa04ad7c84286cfbe98d?s=140&d=retro
Submitted by
demediaMes
over 2 years ago