「6が得られました。in math」
「処理は終わりました」
と表示させたいのですが、以下のコードでうまくいかない原因を教えて頂けると嬉しいです。
他の表示方法もあると思いますが、phpの練習中のため、他のコードでの表示は希望しておらず、
以下のコードに不具合がある点を教えて頂けると嬉しいです。
<?php
$math = new math();//クラス名
$math->change_a(3);
$math->change_b(4);
$math->exec();
echo "処理は終わりました。<br />";
//クラスを定義する
class math{//←クラスtest
private $a;
private $b;
//a+bをして、a-bをしたものを足して出力する
public function exec(){
$res_add = $this->add();//3 + 4 =7
$res_minus = $this->minus();//3 - 4 = -1
$res_total = $res_add + $res_minus;//6
echo $res_total . "が得られました。in math.";
}
public function change_a($buf){
$this->a = $buf;
}
public function change_b($buf){
$this->b = $buf;
}
}
?>
takさんの回答のまんまですけれど、具体的なコードに落とし込んでみました。
質問にあるコードの最後の方に、6行ほど追加しています。
<?php $math = new math();//クラス名 $math->change_a(3); $math->change_b(4); $math->exec(); echo "処理は終わりました。<br />"; //クラスを定義する class math{//←クラスtest private $a; private $b; //a+bをして、a-bをしたものを足して出力する public function exec(){ $res_add = $this->add();//3 + 4 =7 $res_minus = $this->minus();//3 - 4 = -1 $res_total = $res_add + $res_minus;//6 echo $res_total . "が得られました。in math."; } public function change_a($buf){ $this->a = $buf; } public function change_b($buf){ $this->b = $buf; } // ★ここから後を追加しています public function add(){ return $this->a + $this->b; } public function minus(){ return $this->a - $this->b; } }
このコードをそのまま実行すると
PHP Fatal error: Call to undefined method math::add()
と言うエラーで停止します。
$res_add = $this->add();//3 + 4 =7
$res_minus = $this->minus();//3 - 4 = -1
これらの、 $this->add(); $this->minus(); などが定義されていない事が原因です。