Hi,
I have been given some code that has a class with functions in it. I understand some of it but I'm having trouble creating a new instance (a person) in the example code below.
I was wondering if somebody could show me how it is done using the code that is used in the other examples in the code below, and on which line your code would go.
useanimal.php:
<?php
require_once('animal.class.php');
$dog = new Dog("Spot");
$dog->setAge(5);
echo "<p>my name is ".$dog->getName()." and I am a ".$dog->type. ", ".$dog->getAge()." and ".$dog->speak()."</p>";
$cat = new Cat("Tigger");
$cat->setAge(2);
echo "<p>my name is ".$cat->getName()." and I am a ".$cat->type. ", ".$cat->getAge(). " and ".$cat->speak()."</p>";
$anotherCat = new Cat("Tibbles");
$anotherCat->setAge( 7 );
echo "<p>my name is ".$anotherCat->getName()." and I am a ".$anotherCat->type. ", ".$anotherCat->getAge(). " and ".$anotherCat->speak()."</p>";
?>
and the other file is animal.class.php:
<?php
abstract class Animal {
protected $sound;
protected $movement;
public $type;
protected $name;
protected $age;
protected function __construct( $name = null, $type=null, $movement=null, $sound=null ) {
$this->setName( $name );
$this->type = $type;
$this->movement = $movement;
$this->sound = $sound;
}
function move() {
return "I move by {$this->movement}";
}
function speak() {
return "I say {$this->sound}";
}
public function setName( $name ) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setAge( $age ) {
$this->age = $age;
}
public function getAge() {
return "I am {$this->age} years old";
}
}
class Dog extends Animal {
function __construct( $name = null ) {
parent::__construct( $name, 'Dog', 'walking and running', 'woof, woof' );
}
public function getAge() {
return "I am {$this->age} years old, that's " . $this->age * 7 . " human years";
}
}
class Cat extends Animal {
function __construct( $name = null ) {
$this->setName( $name );
$this->type = 'Cat';
$this->movement = "slinking and sliding";
$this->sound = "meiou";
}
}
?>
Any guidance is much appreciated