Tt
Click this widget to change the font size.
CC
Click this widget to change contrast.

Home Page 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | Links | Search | Bio |

Guide to PHP and MySQL (Computer Science 4 All Version)


Chapter 14: Object-Oriented PHP

Classes and Objects

A class is a collection of variables and functions working with these variables. Variables are defined by var and functions by function. Basic class definitions begin with the keyword class, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class. You can use the PHP class keyword to create an object.

<?php
class Book {
  public $isbn;

  public function __construct($isbn) {
    $this->Isbn = $isbn;
  }
} // end book class

$book = new book("978-0743230414");
echo("ISBN: " . $book->Isbn . "<br/>\n");
}
?>

Figure 14-1: A PHP book.class.php Example

class Methods (Functions)

You can then use methods (functions) to perform a task such as "setter" (accessor) and "getter" (mutator) methods. Class variables are referred to as "properties".

<?php
class Book {
  private $author;
  private $copies;
  private $isbn;
  private $ttile;

  public function __construct($isbn) {
    $this->setIsbn ($isbn;
    $this->getAuthor();
    $this->getTitle();
    $this->getNumberCopies();
  }

  public function setIsbn($isbn) {
    $this->isbn = $isbn;
    print("ISBN: " . $this->isbn . "<br/>\n");
  }

  public function getAuthor() {
    $this->author = "Tarantula";
    print("Author: " . $this->author . "<br/>\n");
  }

  public function getTitle() {
    $this->title = "Tarantula";
    print("Title: " . $this->title . "<br/>\n");
  }

  public function getNumberCopies() {
    $this->copies = 5;
    print("Number of Copies Available: " . $this->copies . "<br/>\n");
  }
} // end book class

$book = new book("978-0743230414");
echo("ISBN: " . $book->Isbn . "<br/>\n");
}
?>

Figure 14-2: book.class.php Code
ISBN: 978-0743230414
Author: Bob Dylan
Title: Tarantula
Number copies available: 5

Figure 14-3: book.class.php Output

Help contribute to my OER Resources. Donate with PayPal button via my PayPal account.
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Copyright © 2016-2024 Jim Gerland