At first, PHP wasn't an
object-oriented (OO) language. As it evolved, more and more object-oriented
features appeared. First, you could define classes, but there were no
constructors. Then, constructors appeared, but there were no destructors. Slowly
but surely, as more people began to push the limits of PHP's syntax, additional
features were added to satisfy the demand.
However, if you're the type of person who wishes PHP to be a
true OO language, you'll probably be disappointed. At its heart, PHP is a
procedural language. It isn't Java. But, if you're the type of person who wants
to use some OO features in your code, PHP is probably right for you.
A class is a package containing two things:
data and methods to access and modify that data. The data portion consists of
variables; they're known as properties. The other part of a class is a
set of functions that can alter a class' properties; they're called
methods.
When we define a class, we don't define an object that can be
accessed and manipulated. Instead, we define a template for an object. From this
blueprint, we create malleable objects through a process known as
instantiation . A program can
have multiple objects of the same class, just as a person can have more than one
book or many pieces of fruit.
Classes also live in a defined hierarchy. At the top of the chain, there is a generic class.
In PHP, this class is named stdClass, for
"standard class." Each class down the line is more specialized than its parent.
For example, a parent class could be a building. Buildings can be further
divided into residential and commercial. Residential buildings can be further
subdivided into houses and apartment buildings, and so forth.
Both houses and apartment buildings have the same set of
properties as all residential buildings, just as residential and commercial
buildings share some things in common. When classes are used to express these
parent-child relationships, the child class inherits the properties and methods
defined in the parent class. This allows you to reuse the code from the parent
class and requires you to write code only to adapt the new child to its
specialized circumstances. This is called inheritance and is one of the major advantages of
classes over functions. The process of defining a child class from a parent is
known as subclassing or
extending.
Objects play
another role in PHP outside their traditional OO position. Since PHP can't use
more than one namespace, the ability for a class to package multiple properties
into a single object is extremely helpful. It allows clearly demarcated separate
areas for variables.
class guest_book {
var $comments;
var $last_visitor;
function update($comment, $visitor) {
...
}
}