Reputation: 294
I'm trying to get my head around constructors and PHP in general, but what I'm trying to achieve here is a way of calculating the volume, diameter and area of a circle with PI
and FOUR_THIRDS
as constants in the class.
My code keeps saying there is an error with the constants saying they are undefined but I copied the method from php.net. Then the $radius
is also showing up as an undefined variable, so should I add $radius = 1;
somewhere into the class to define it, is that what it means by defining?
<?php
class SphereCalculator {
const PI = 3.14;
const FOUR_THIRDS =4/3;
public function __construct($radius){
$this->classRadius = $radius;
}
public function setRadius ($radius){
$this->classRadius = $radius;
}
public function getRadius(){
return $this->classRadius;
}
public function getVolume () {
return FOUR_THIRDS * PI * ($this->classRadius * $this->classRadius);
}
public function getArea () {
return PI * ($this->classRadius * $this->classRadius);
}
public function getDiameter () {
return $this->classRadius += $this->classRadius;
}
}
$mySphere = new SphereCalculator ();
$newRadius =$mySphere->radius;
$newRadius = 113;
echo "The volume of the circle is ".$mySphere->getVolume ()."<br>";
echo "The diameter of the circle is ".$mySphere->getDiameter ()."<br>";
echo "The area of the circle is ".$mySphere->getArea ()."<br>";
?>
Upvotes: 0
Views: 3452
Reputation: 326
You need to define constant FOUR_THIRDS
as floating value or integer value. You have defined with as 4/3
which is not acceptable.
Hence, you need to define as,
const PI = 3.14;
const FOUR_THIRDS = 1.33;
Since you have defined the constants inside the class, it takes it as member variable of the class itself. Hence, you will need to access the constants with self::PI
.
Other problem with your php code is your defining the constructor wrong. You have an paramter while defining the constructor but in your main part of the code where you created the object, you have not passed the parameter.
Here is the link to the corrected PHP code: https://ideone.com/UOMUPf
Upvotes: 1
Reputation: 139
You should use constants using class name like ClassName::ConstantName
, and if you are using within the class then you can use as self::ConstantName
.
So, you should use your constants as self::PI
and self::FOUR_THIRDS
.
Upvotes: 0