我是php新手并尝试使用Factory Method。 我想使用' build'来实例化我的班级形状。功能,这样,当班级' Circle'实例化其面积和周长是否计算,如果类'矩形'被称为,其面积和周长被计算并返回。 这是我到目前为止以及我想要实现的目标。这不起作用,我相信有更好的方法可以做到这一点!
$allmyshapes = Shapes::build($initData);
foreach($allmyshapes as $value) {
if ($value =='Circle'){
$x = new Circle();
echo $x::area();
echo $x::circumference();
}
if ($value =='Rectangle'){
$y = new Rectangle();
echo $y::area();
echo $y::circumference();
}
}
我的班级:
class Shapes {
public static function build($initData){
}
foreach($newlist as $value){
if($value[0]=='Circle'){
$shape1 =new Circle($value[1],$value[2]);
}
if($value[0]== 'Rectangle'){
$shape2 =new Rectangle($value[1],$value[2]);
}
}
return array($shape1,$shape2);
}
}
class Circle extends Shapes {
public $radius;
public $centre_point;
public function __construct($radius, $centre_point) {
$this->radius = $radius;
$this->centre_point = $centre_point;
}
public function area(){
return (pi() *$this->radius * $this->radius);
}
public function circumference(){
return 2 * pi() *$this->radius;
}
}
class Rectangle extends Shapes {
public $x;
public $y;
public function __construct($x, $y) {
$this->x= $x;
$this->y = $y;
}
public function area() {
return $this->x * $this->y;
}
public function circumference() {
return 2 * ($this->x+ $this->y);
}
}
答案 0 :(得分:0)
您的课程没有任何问题,就是您使用它们输出信息的方式:
class Shapes {
public static function build($initData){
//$initdata is a heredoc
$newlist = explode("\n", $initData);
foreach($newlist as $key => $initData){
$newlist[$key] = explode("\t", $initData);
}
foreach($newlist as $value){
if($value[0] == 'Circle'){
$shape1 = new Circle($value[1], $value[2]);
}
if($value[0] == 'Rectangle'){
$shape2 = new Rectangle($value[1], $value[2]);
}
}
return array($shape1, $shape2);
}
}
class Circle extends Shapes {
public $radius;
public $centre_point;
public function __construct($radius, $centre_point){
$this->radius = $radius;
$this->centre_point = $centre_point;
}
public function area(){
return (pi() * $this->radius * $this->radius);
}
public function circumference(){
return 2 * pi() * $this->radius;
}
public function draw(){
return ( $this->radius.":".$this->centre_point);
}
}
class Rectangle extends Shapes {
public $x;
public $y;
public function __construct($x, $y){
$this->x = $x;
$this->y = $y;
}
public function area(){
return $this->x * $this->y;
}
public function circumference(){
return 2 * ($this->x + $this->y);
}
}
$initData = <<<ENDINIT
Circle 5 2
Rectangle 5 10
Ellipse 10 10 4 5
ENDINIT;
$allmyshapes = Shapes::build($initData);
foreach($allmyshapes as $value){
if(get_class($value) === 'Circle'){
echo nl2br("**Circle**\nArea: ".$value->area()."\nCircumference: ".$value->circumference()."\n");
}
if(get_class($value) === 'Rectangle'){
echo nl2br("**Rectangle**\nArea: ".$value->area()."\nCircumference: ".$value->circumference()."\n");
}
}
我为您提供的代码添加了2个功能get_class()
&amp; nl2br()
。如果您在CLI格式中使用此nl2br
,则可以删除get_class()
,但其主要功能是在使用Web浏览器查看输出时输出可读性。
{{1}}将解决您尝试找出在创建对象时使用的构造函数的问题。