Jump to content

Getters And Setters & Constructor


lhynx31

Recommended Posts

Hi. I'm just a starter on php, i would like to ask on how to display the string that I assigned in my constructor.

 

Car.php

class Car {
private $color;
private $horsepower;
private $seats;

public function getColor() {
 return $this->color;
}
public function setColor($color) {
 $this->color = $color;
}
public function getHorsepower() {
 return $this->horsepower;
}
public function setHorsepower($horsepower) {
 $this->horsepower = $horsepower;
}
public function getSeats() {
 return $this->seats;
}
public function setSeats($seats) {
 $this->seats = $seats;
}
}

 

RaceCar.php

class RaceCar extends Car {
function __construct() {
 $this->setColor("red");
 $this->setHorsepower("23");
 $this->setSeats("four");
}
}

 

and the index.php where I call them,

 

index.php

<body>
 <?php
 include_once('Car.php');
 include_once('RaceCar.php');

 $raceCar = new RaceCar();

 echo "color: " + $raceCar->getColor();
 echo "horsepower: " + $raceCar->getHorsepower();
 echo "seats: " + $raceCar->getSeats();
 ?>
</body>

Link to comment
https://forums.phpfreaks.com/topic/272226-getters-and-setters-constructor/
Share on other sites

Not really sure what string your referring to as you have 3 potential strings. You can define a "toString()" method giving a generic string to display the state of your object; this is similar to the toString method in Java and it works really well.

osted Today, 11:38 PM You're using the wrong concatenation symbol. In PHP you'll need to use a period (.) to concatenate two strings, using a plus (+) will make PHP attempt to cast the values to numerical values.

 

Hi. Thanks for the help, i was just finished my java study so i have accidentally mixed them.. sorry about that, and thanks for your help.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.