0

我在这段代码上投入了大约 4 个小时,但在代码片段正常运行时没有得到所需的结果。代码如下:

trait CircleShape{
    public function input($radius){
        $this->$radius = $radius;
    }
}

trait AngleShape{
    public function input($height, $width){
        $this->$height = $height;
        $this->$width = $height;
    }
}

trait GeneralMethod{
    public function get($property){
        return $this->$property;
    }
}

class Shape{
    private $height, $width, $radius;
    const PI = 3.1415;

    use GeneralMethod, AngleShape, CircleShape{
        AngleShape::input insteadof CircleShape;
        CircleShape::input as inputCircle;
    }
}

class Circle extends Shape{
    public function area(){
        return parent::PI * $this->get('radius') * $this->get('radius'); 
    }       
}

class Rectangle extends Shape{

    use GeneralMethod, AngleShape, CircleShape{
        AngleShape::input insteadof CircleShape;
        CircleShape::input as inputCircle;
    }
    public function area(){
        return $this->get('height') * $this->get('width'); 
    }       
}

$rect = new Rectangle;
$rect->input(12, 2);
Echo "Area: " . $rect->area() . "\n";

$cir = new Circle;
$cir->inputCircle(10);
Echo "Circle Area : " . $cir->area() . "\n";

此代码中的逻辑错误是什么?为什么我得到以下输出:

Rectangle Area : 0
Circle Area : 0
4

2 回答 2

4
$this->$radius = $radius;

应该

$this->radius = $radius;

与 和$height相同$width

于 2012-05-22T14:35:24.833 回答
0

在这里,您正在尝试使用伪变量 $this 和箭头运算符 (->) 来调用一个变量,那么您应该在变量前面放下 $

于 2013-10-21T05:14:13.897 回答