我很震惊于在level2上从继承的子进程中重载了父类的方法。
abstract class parent
-> child1 extends parent
-> final class child2 extends child1
我想重载parent
child2
的方法
abstract class Shape
{
protected $length;
protected $height;
protected $a;
protected $b;
protected $c;
public function getCoordinates($length,$height)
{
$this->length=$length;
$this->height=$height;
}
public function getSides($a,$b,$c)
{
$this->a=$a;
$this->b=$b;
$this->c=$c;
}
abstract public function area();
abstract public function perimeter();
abstract public function display();
}
class rectangle extends Shape
{
public function area()
{
return round(($this->length)*($this->height),2);
}
public function perimeter()
{
return round(2*(($this->a)+($this->b)),2);
}
public function display()
{
echo "area is :". rectangle::area() . "<br>";
echo "perimeter is : ". rectangle::perimeter() ."<br>";
}
}
final class triangle extends rectangle
{
function __call($method_name, $arguments) // this is wrong ........please modify here to call area(),which is in shape class();
{
$accepted_methods = array("getCoordinates","area","perimeter");
}
public function area()
{
return round((($this->length)*($this->height)*($this->width)/2),2);
}
public function perimeter()
{
return round((($this->a)+($this->b)+($this->c)),2);
}
public function getCoordinates($length,$height,$width)
{
$this->length=$length;
$this->height=$height;
$this->width=$width;
}
public function display()
{
echo "area is :". triangle::area() . "<br>";
echo "perimeter is : ". triangle::perimeter() ."<br>";
}
}
$r=new rectangle();
$r->getCoordinates(1,2,4);
$r->getSides(6,2);
$r->display();
$ot = new triangle();
$ot->getCoordinates(1,2,4);
$ot->getSides(6,2,3);
$ot->display();
?>
提前致谢
答案 0 :(得分:0)
$r->getSides(6,2);
你的抽象课要求三个论点!此外,该功能实际上是一个setter方法。你应该将它命名为setSides();.与getCoordinates()相同。
更新:我认为您将继承与重载混淆。以下是使用__call重载的示例。我认为这不是你想要做的,而是你在你的例子中所拥有的。也许这会有所帮助。
abstract class overloadTestAbstract {
public function printOne($show) {
echo __METHOD__ . ': ' . $show . '<br />';
}
}
class overloadTestOne extends overloadTestAbstract {
public function __call($method,$arguments) {
$methods = array('printOne','printTwo','printThree');
if ( in_array($method,$methods) ) {
echo __METHOD__ . ' :OVERLOAD METHOD: ' . $arguments[0] . '<br />';
} else {
echo 'We are so sorry, but this method is available';
}
}
public function printTwo($show) {
echo __METHOD__ . ': ' . $show . '<br />';
}
}
然后,如果你这样做:
$test = new overloadTestOne();
$test->printOne('Hello World');
$test->printTwo('Goodbye World');
$test->printThree('Hello World, again');
$test->printFour('Goodbye World, again');
你会得到这个
// print results
'overloadTestAbstract::printOne: Hello World'
'overloadTestOne::printTwo: Goodbye World'
'overloadTestOne::__call :OVERLOAD METHOD: Hello World, again'
'We are so sorry, but this method is available'
虽然我在重载__call中将printOne和printTwo作为可接受的方法,但由于已经定义了这些方法,因此它们不会被使用,它们由现有方法按预期处理。另一方面,printThree因为该方法不存在而被重载。与printFour相同,但该方法无意打印参数。使用可接受的方法定义的数组没有做任何事情。它只是一个数组。你必须为这些方法分配一些任务或者像我一样返回一些错误。