今天学习PHP到面向对象啦~~~~~由于有C++基础,所以面向对象思想不用话太多时间,接下来直接给题目和编程代码。
题目如下:
1.创建一个名为baseCalc的类,它存储了两个数字作为属性。接下来,创建一个calculate()的方法,该方法向浏览器显示数字。
刚看题目,这还不简单?!于是乎就马上码了下面的代码:
<?php
class baseCalc {
private $num1;
private $num2;
function baseCalc($n,$m){ //初始化数据
$this->num1=$n;
$this->num2=$m;
}
public function calculate(){ //方法的实现
echo "<hr/>"."This is parent class: "."<br/>";
echo "We will calculate the numbers: ".$this->num1." and ".$this->num2."<br/>";
echo "<hr/>";
}
}
$myclass1=new baseCalc(8,4); //实例化对象
$myclass1->calculate(); //调用方法
?>
运行结果如下:
题目2:为题目1中的类创建名为addCalc(),subCalc(),mulCalc(),divCalc()的方法,它们覆盖了calculate()方法,并想浏览器显示相应的计算结果。
刚拿到题目,用这么多个方法去覆盖一个方法?这题目没有问题么?后来想想,题目是不是要表达这个意思呢?
来,我们来看看代码:
<?php
class baseCalc {
private $num1;
private $num2;
function baseCalc($n,$m){ //初始化数据
$this->num1=$n;
$this->num2=$m;
}
protected function addCalc(){ //新增的方法
echo "call function addCalc(): num1+num2=".($this->num1+$this->num2)."<br/>";
}
protected function subCalc(){
echo "call function subCalc(): num1-num2=".($this->num1-$this->num2)."<br/>";
}
protected function mulCalc(){
echo "call function mulCalc(): num1*num2=".($this->num1*$this->num2)."<br/>";
}
protected function divCalc(){
echo "call function divCalc(): num1/num2=".($this->num1/$this->num2)."<br/>";
}
public function calculate(){ //方法的实现
echo "<hr/>"."This is parent class: "."<br/>";
echo "We will calculate the numbers: ".$this->num1." and ".$this->num2."<br/>";
echo "<hr/>";
}
}
$myclass1=new baseCalc(8,4); //实例化对象
$myclass1->calculate(); //调用方法
class childclass extends baseCalc{ //继承父类
public function calculate(){ //覆盖原来的方法
echo "<hr/>"."This is child class: "."<br/>";
$this->addCalc();
$this->subCalc();
$this->mulCalc();
$this->divCalc();
echo "<hr/>";
}
}
$myclass2=new childclass(8,4); //实例化子类对象
$myclass2->calculate(); //调用方法
?>
运行结果如下:
总结:对于题目2,其实也可以将addCalc(),subCalc(),mulCalc(),divCalc()方法在子类中添加,然后在子类覆盖调用即可,这样不改变父类二进行扩展,更利于项目开发的和维护。