Guide to PHP and MySQL (University at Buffalo Version)


Chapter 14: Object-Oriented PHP

Classes and Objects

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) methidss. 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
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Copyright © 2018 Jim Gerland