Working with objects

learning about Objects. I’m suppose to include 2 methods: talk (bark) and move(run, walk). Would I use constructors? This is what I am trying to do but getting the following error message: Fatal error: Cannot redeclare pet::__constructor() on line 43. What does this mean?

I’m suppose to then call the talk and move methods.

[php]<?php

class pet{
private $type;
private $name;
private $breed;
private $color;
private $talk;
private $move;

//set

public function setType($x){
	$this->type=$x;

}
public function setName($x){
$this->name=$x;
}
public function setBreed($x){
$this->breed=$x;
}
public function setColor($x){
$this->color=$x;
}
//get
public function getType(){
return $this->type;
}
public function getName(){
return $this->name;
}
public function getBreed(){
return $this->breed;
}
public function getColor(){
return $this->color;
}

public function __constructor ($bark){
	echo "$name can you $talk?";
}

public function __constructor($run){
	echo " run!";
}	

}
?>

Objects <?php

$PetObject = new pet();

$PetObject->setType("Dog ");
echo $PetObject->getType();

$PetObject->setName("Fido ");
echo $PetObject->getName();

$PetObject->setBreed("German Shepherd ");
echo $PetObject->getBreed();

$PetObject->setColor(“yellow”);
echo $PetObject->getColor();

?>

[/php]

A class can have one constructor, it’s a magic method that runs on instantiation.

Method is just a normal function used in the context of a class/object.

so just do something like

[php]public function bark() {}
public function run() {}[/php]

[hr]

Also this won’t work

[php] public function __constructor ($bark){
echo “$name can you $talk?”;
}[/php]

In that function/method scope you only have $bark and $this available. You can reach $name and $talk through $this (the class)

[php] public function __constructor ($bark){
echo “$this->name can you $this->talk?”;
}[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service