PHP特征:本代码中的逻辑错误是什么

时间:2012-05-22 14:32:29

标签: php traits

我已在此代码上投入了大约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

2 个答案:

答案 0 :(得分:4)

$this->$radius = $radius;

应该是

$this->radius = $radius;

$height$width相同。

答案 1 :(得分:0)

这里你试图用伪变量$ this和箭头操作符( - >)来调用一个变量然后你应该在变量前面放下$

相关问题