Objects
PHP has limited support for object-oriented programming and allows programmers to define their own classes and create object instances of those classes. We make little use of objects in this book, and this section serves as an introduction to PHP’s support of object-oriented features. The subject of object-oriented programming is extensive, and we don’t provide a complete explanation of the subject here.
Classes and Objects
A class
defines a compound data structure made up of member variables and a
set of functions—known as methods or member
functions—that operate with the specific structure. Example 2-7 shows how a class Counter
is defined in PHP. The class Counter contains
two member variables—the integers $count
and
$startPoint
—and four functions that use
these member variables. Collectively, the variables and the functions
are members of the class Counter.
Example 2-7. A simple class definition of the user-defined class Counter
<?php // A class that defines a counter. class Counter { // Member Variables var $count = 0; var $startPoint = 0; // Methods function startCountAt($i) { $this->count = $i; $this->startPoint = $i; } function increment( ) { $this->count++; } function reset( ) { $this->count = $this->startPoint; } function showvalue( ) { print $this->count; } } ?>
To use the data structures and functions defined in a class, an instance of the class—an object—needs to be created. Like other data types—integers, strings, arrays, and so on—objects are held by variables. ...
Get Web Database Applications with PHP, and MySQL now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.