-4

Doing some OO PHP. I'm getting undefined variables on line 11 and 31 and I'm not sure why.

http://pastebin.com/D0rNWdn3

<?php 

    class geometricObject {
        private $color;

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

        public function getColor(){
            return $color;
        }

        public function setColor($color){
            $this->color = $color;
        }
    }

    class circle extends geometricObject {
        private $radius;

        public function __construct($radius, $color){
            parent::__construct($color);
            $this->radius = $radius;
        }

        public function getRadius(){
            return $radius;
        }

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

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

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

?>

<?php 

    include_once 'templates/classes.php';

    $myCircle = new circle(10, "green");

    $circleArea = $myCircle->getArea();

    $color = $myCircle->getColor();

    include_once 'output.php';

?>

<html>
<body>

<?php echo $circleArea; echo $color; ?>

</body>
</html>
hakre
  • 193,403
  • 52
  • 435
  • 836
user1683645
  • 1,467
  • 1
  • 20
  • 26
  • 2
    Please include code *in your question* in future – Jon Skeet Dec 22 '12 at 13:31
  • Yes, but it should have been *in the question*. We shouldn't have to follow links to code when it's perfectly easy to include code in the original post. (You could have posted a *shorter* example, too.) – Jon Skeet Dec 22 '12 at 13:33
  • 1
    Possible duplicate of [PHP: “Notice: Undefined variable” and “Notice: Undefined index”](http://stackoverflow.com/q/4261133/367456) – hakre Dec 22 '12 at 13:47

3 Answers3

2

You forgot $this->

return $this->color;
Codler
  • 10,951
  • 6
  • 52
  • 65
2

You're getting the error because $color is undefined within the method scope. You only pass the $color argument to the constructor and the setColor method.

To access it in other class methods you would use $this->color not $color

David Barker
  • 14,484
  • 3
  • 48
  • 77
1

You have forgot $this before that variables you should do it this way: return $this->color;

Mustafa Shujaie
  • 806
  • 2
  • 10
  • 18