2012-05-22 69 views
0

我已经投入了大约4小时的代码,但在代码片段正常运行时没有获得所需的结果。代码如下:PHP特质:此代码中的逻辑错误是什么

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 
+0

你定义和使用获得的方式($的道具)里面的功能对我来说看起来很陌生。你为什么这样做?如果你想避免名称冲突的属性,你至少应该在该函数中做一些名字混搭。否则,get()的好处可以忽略不计。 – smarr

回答

4
$this->$radius = $radius; 

应该

$this->radius = $radius; 

而且同样具有$height$width

+0

哇!我只是在几秒钟内完成改变和问题。我也理解我所做的逻辑和错误。非常感谢你。 –

+0

您应该只是关闭警告。它会通过在这里生成一个'未定义的属性'来保护你免于这些错误? – Nanne

0

这里你被伪变量$ this和箭头操作符试图( - >)调用一个变量,那么你应该下车$在前方可变