I'm trying OO in PHP. I think I understand what goes wrong but I don't understand how to fix it.
class Name {
public $_firstname;
public $_lastname;
public function setName($firstName, $lastName){
$this->_firstname = $firstName;
$this->_lastname = $lastName;
}
public function getName(){
echo 'The full name is '. $this->_firstname. ' ' . $this->_lastname .'<br>';
}
}
class Description extends Name{
public $_desciprion;
public function setDescription($description){
$this->_desciprion = $description;
}
public function getDescription(){
echo $this->_desciprion. ' is written by '.$this->_firstname .'<br>';
}
}
$firstNames = array("some", "another", "john");
$lastNames = array("body", "body", "doe");
$descriptions = array("description 1", "description 2", "description 3");
for ($i=0; $i < count($firstNames); $i++){
$name = new Name();
$name->setName($firstNames[$i], $lastNames[$i]);
$description = new Description();
$description->setDescription($descriptions[$i]);
echo $description->getDescription();
}
I want to echo the $description
containing the $_firstname
of the Name
class.
I don't really know the OO way to fill it.
Thoughts?
In your case $name
is completely unrelated to $description
. However, this is easily fixed:
for ($i=0; $i < count($firstNames); $i++){
$description = new Description();
$description->setName($firstNames[$i], $lastNames[$i]);
$description->setDescription($descriptions[$i]);
echo $description->getDescription();
}
Bonus improvement:
foreach ($firstNames as $i => $firstName){
$description = new Description();
$description->setName($firstName, $lastNames[$i]);
$description->setDescription($descriptions[$i]);
echo $description->getDescription();
}
for ($i=0; $i < count($firstNames); $i++){
$description = new Description();
$description->setName($firstNames[$i], $lastNames[$i]);
$description->setDescription($descriptions[$i]);
echo $description->getDescription();
}
You are setting the name to another instance ( $name ) in order to set the name to the description object you have to write:
for ($i=0; $i < count($firstNames); $i++){
$description = new Description();
$description->setName($firstNames[$i], $lastNames[$i]);
$description->setDescription($descriptions[$i]);
echo $description->getDescription();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.