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
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.

Edited by CPD
Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.