This page demonstrates PHP object-oriented features


<?php
  // class names are case-insensitive
class Point {
  private $x;
  private $y;
  static $grid_size = 100;

  function __construct($x = 0, $y = 0) {
    if ($this->check_coords($x, $y)) {
      print "Point constructor\n";
      $this ->x = $x;
      $this ->y = $y;
    }
  }

  private function check_coords($x, $y) {
    if ($x < 0 || $y < 0 || $x > Point::$grid_size || $y > Point::$grid_size)
      return false;
    return true;
  }

  function printp() {
    print "\$x = $this->x \$y = $this->y<br />\n";
  }

  function move($dx, $dy) {
    if ($this -> check_coords($this ->x + $dx, $this ->y + $dy)) {
      $this ->x += $dx;
      $this ->y += $dy;
    }
  }
}

?>


<?php
require_once("Point.php");

class ColorPoint extends Point {
  private $color;

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

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

  function printp() {
    parent::printp();
    print "{$this -> color} <br />\n";
  }
}
?>


<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>
Testing a point class
</title>
<body>
<h2>Testing a point class</h2>
<p>
<?php
require_once("Point.php");
require_once("ColorPoint.php");

$point1 = new Point(1,3);
print "point1: ";
$point1->printp();

$point2 = new Point();
print "point2: ";
$point2->printp();

$point2->move(5, 7);
print "point2 after the move: ";
$point2->printp();

$color_point = new ColorPoint(3, 7, "red");
print "color point: ";
$color_point->printp();
?>
</p>
</body>
</html>

http://csci1101sp10.morris.umn.edu/~elenam/tmp4657sp11/testPoints.php

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.