Google News
logo
PHP program to Class constants
In the following example of PHP program to demonstrate the usage of class constants :
Program :
<?php
class Circle {
  const PI = 3.14159265359;
  private $radius;

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

  public function area() {
    return self::PI * $this->radius * $this->radius;
  }
}

// Create a circle object with radius 5
$c = new Circle(5);

// Print the area of the circle
echo "Area of circle with radius ".$c->radius." is ".$c->area()."\n";
?>
In this example, we define a `Circle` class with a constant `PI` and a private member variable `$radius`. The constructor takes a radius parameter and sets the radius value for the object. The `area()` method calculates and returns the area of the circle.

We then create a `Circle` object with radius 5 and call the `area()` method to calculate and print the area of the circle. The `self::PI` expression is used to access the value of the `PI` constant within the class.