在php中练习Loose'ly耦合代码

时间:2017-09-07 09:10:51

标签: php

我是PHP或任何编程语言的新手,我实际上是如何编写松耦合

<?php

    interface IPolygon{
        public function getArea();
    }

    class Polygon{

        private $ipolygon;

        public function __construct(IPolygon $ipolygon){
            $this->ipolygon = $ipolygon;
        }

        public function calArea(){
            return this->ipolygon->getArea();
        }
    }

    class Circle implements IPolygon{

        private $radius;
        private $pi = 3.14;

        public function __construct($radius){
            $this->radius = $radius;
        }

        public function getArea(){
            return $pi*$radius*$radius;
        }
    }

    class Triangle implements IPolygon{

        private $base;
        private $height;

        public function __construct($base , $height){
            $this->base = $base;
            $this->height = $height;
        }

        public function getArea(){
            return $base*$height/2;
        }
    }


    $c = new Circle(14);
    $p = new Polygon($c);

    echo "<hr />";
    $p->calArea();
?>

错误

Notice: Undefined variable: ipolygon in C:\xampp\htdocs\OOP\Polygon.php on line 16

注意:未定义的变量:第30行的C:\ xampp \ htdocs \ OOP \ Polygon.php中的pi

注意:未定义的变量:第30行的C:\ xampp \ htdocs \ OOP \ Polygon.php中的半径

注意:未定义的变量:第30行的C:\ xampp \ htdocs \ OOP \ Polygon.php中的半径

有人能解释我是怎么做到的?

1 个答案:

答案 0 :(得分:0)

作为一般规则,所有类属性都使用$this->

引用

这意味着:

<?php

    interface IPolygon{
        public function getArea();
    }

    class Polygon{

        private $ipolygon;

        public function __construct(IPolygon $ipolygon){
            $this->ipolygon = $ipolygon;
        }

        public function calArea(){
            return $this->ipolygon->getArea();
        }
    }

    class Circle implements IPolygon{

        private $radius;
        private $pi = 3.14;

        public function __construct($radius){
            $this->radius = $radius;
        }

        public function getArea(){
            return $this->pi*$this->radius*$this->radius;
        }
    }

    class Triangle implements IPolygon{

        private $base;
        private $height;

        public function __construct($base , $height){
            $this->base = $base;
            $this->height = $height;
        }

        public function getArea(){
            return $this->base*$this->height/2;
        }
    }


    $c = new Circle(14);
    $p = new Polygon($c);

    echo "<hr />";
    $p->calArea();

有效:http://sandbox.onlinephpfunctions.com/code/e7f79bb186ffac952ebc4c2b5a8098e1efaeb874