私は一般的にコンストラクタとPHPの周りに頭を抱えようとしていますが、ここで達成しようとしているのは、クラスの定数としてPI
とFOUR_THIRDS
の円の体積、直径、面積を計算する方法です。PHP:円の体積、直径、面積を計算するには?
私のコードでは、定数が定義されていないとのエラーが出ていますが、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' 'として参照されるか、または ';グローバル定数は 'FOUR_THIRDS'として参照されています....クラス定数を定義しました –
直径については、 '+ ='を使わないで ''単純に '+'を使用してください。それ以外の場合は 'getDiameter()'を呼び出すたびに 'classRadius'プロパティの値を実際に倍にします –
また、' * $ this-> classRadius' - ボリュームは4/3 PI R^3です –