PHP:如何计算圆的体积、直径和面积


PHP: How to calculate the volume, diameter and area of a circle?

我试图了解构造函数和PHP,但我在这里试图实现的是一种计算圆的体积、直径和面积的方法,其中PIFOUR_THIRDS是类中的常数。

我的代码一直说常量有一个错误,说它们是未定义的,但我从php.net复制了这个方法。然后$radius也显示为一个未定义的变量,所以我应该在类的某个地方添加$radius = 1;来定义它吗?这就是定义的意思吗?

<?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>";

?>

您需要将常量FOUR_THIRDS定义为浮点值或整数值。您已将定义为4/3,这是不可接受的。

因此,您需要定义为,

const PI = 3.14;
const FOUR_THIRDS = 1.33;

由于您已经在类中定义了常量,因此它将其作为类本身的成员变量。因此,您需要使用self::PI访问常量。

php代码的另一个问题是您定义了错误的构造函数。在定义构造函数时,您有一个参数,但在创建对象的代码的主要部分中,您没有传递参数。

以下是更正后的PHP代码的链接:https://ideone.com/UOMUPf

您应该使用类似ClassName::ConstantName的类名来使用常量,如果您在类中使用,则可以使用作为self::ConstantName

因此,您应该将常量用作self::PIself::FOUR_THIRDS