0

I am trying to add a value to a public variable inside a class using a function. I am unsure how to do so. My current PHP code is as follows:

class Truck {
public $Odometer = 0;
public $Model = 'Triton';
public $Price;
public $Horsepower;

public function __construct() {
  $this->Price = 30;
}
public function __construct() {
  $this->Horsepower = 205;
}
public function ShowOdometer() {
  echo "Odometer: ".$this->Odometer;
}
public function ShowModel() {
  echo "Model: ".$this->Model;
}
public function ShowPrice() {
  echo "Cost: ".$this->Price;
}
public function ShowHorsepower() {
  echo "Horsepower: ".$this->Horsepower
}
}

am attempting to add an integer value to $Price and $Horsepower through a method. I have attempted to use __construct() although this gives me a Fatal error: Cannot redeclare Truck::__construct().

2
  • 1
    as error say Cannot redeclare Truck::__construct(). a class has single construct() function. Commented Mar 4, 2016 at 10:03
  • 1
    You just can't have the constructor twice, otherwise everything is ok. (Also a variable in a class is called a property; And a function a method) Commented Mar 4, 2016 at 10:03

1 Answer 1

2

You are defining two constructor inside the class, thus the error - Fatal error: Cannot redeclare Truck::__construct(). Try -

class Truck {
public $Odometer = 0;
public $Model = 'Triton';
public $Price;
public $Horsepower;

public function __construct() {
  $this->Price = 30;
  $this->Horsepower = 205;
}
public function ShowOdometer() {
  echo "Odometer: ".$this->Odometer;
}
public function ShowModel() {
  echo "Model: ".$this->Model;
}
public function ShowPrice() {
  echo "Cost: ".$this->Price;
}
public function ShowHorsepower() {
  echo "Horsepower: ".$this->Horsepower
}
}
Sign up to request clarification or add additional context in comments.

5 Comments

You are right about the constructor, but its also possible(if he needs more then 1 constructor) to just name the 2nd 1 different? like constructor2?
Thank you for your answer; and all the others that commented above. This has solved this particular issue! What must I do to make sure that the function of __construct() runs and updates the values so I can use ShowHorsePower?
@baboizk. Then that will be member function of that class. Which is normal. But you can't have two constructor for same class.
@Sougata I have to read into that then, thank you. not familiar with what that means. I've been using an API class at the moment and it then has alot of "member functions".
I would suggest you to go through OOP concepts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.