Objects and classes in php

Class definition, class inheritance


<?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)) {
      $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 = ($this -> x) + $dx;
      $this ->y = ($this -> y) + $dy;
    } else {
      print "cannot move a point outside of the grid";
    }
  }
}

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";
  }
}
?>

Using objects


<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- 
PHP object-oriented features
Author: Elena Machkasova 
Last modified: 5/6/08
--> 
<html  xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>

Testing a point class
</title>
</head>
<body>
<h2>Testing a point class</h2>
<p>
<?php
require_once("point.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://csci1101sp09.morris.umn.edu/~elenam/1101_spring09/objects/test_point.php


UMM CSci 1101

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.