Guide to PHP and MySQL (University at Buffalo 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.
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");
}
?>
book.class.php
Exampleclass
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".
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");
}
?>
book.class.php
CodeAuthor: Bob Dylan
Title: Tarantula
Number copies available: 5
book.class.php
Output