Search code examples
phpoopstaticprotected

I want to use in oop with protected static


I am learning oop. I try to cover the oop and to understand the idea behind oop. I have code and i want to use with protect static for an understanding. I Declare attributes: protected static $formula . And I call to protected static $formula by self :: $formula = $this->width * $this->height;. When I run the code in debuger I got $formula = null. `$formula' should be = 10000. I don't know why ? Thanks for any help. Here is my code:

<?php
Class Rectangle {

//Declare the attributes:
public $width = 0;
public $height = 0;
protected static $formula = 0;

//Method to set the dimensions.
Function set_size($w = 0, $h = 0) {
        $this->width = $w;
        $this->height = $h;
        self :: $formula = $this->width * $this->height;
}

//Method to calculate and return the area.
function get_area() {
            $this->set_size(100,100);
    return ($formula);
    }

}

$rect = new Rectangle ();
echo $rect->get_area();

?>


Solution

  • Your code has a small bug in get_area:

    return ($formula);
    

    Should be:

    return self::$formula;