Declaring a Class
To
design your program or code library in an object-oriented fashion,
you’ll need to define your own classes, using the
class keyword. A class definition includes the class name and the
properties and methods of the class. Class names are case-insensitive
and must conform to the rules for PHP identifiers. The class name
stdClass
is reserved. Here’s
the syntax for a class definition:
classclassname
[ extendsbaseclass
] { [ var$property
[= value
]; ... ] [ functionfunctionname
(args
) { //code
} ... ] }
Declaring Methods
A
method is a function defined inside a class. Although PHP imposes no
special restrictions, most methods act only on data within the object
in which the method resides. Method names beginning with two
underscores (__
) may be used in the future by PHP (and are currently used
for the object serialization methods _ _sleep( )
and _ _wakeup( )
, described later in this
chapter), so it’s recommended that you do not begin
your method names with this sequence.
Within a method, the $this
variable contains a reference to the object on which the method was
called. For instance, if you call $rasmus->birthday( )
, inside the birthday( )
method,
$this
holds the same value as
$rasmus
. Methods use the $this
variable to access the properties of the current object and to call
other methods on that object.
Here’s a simple class definition of the
Person
class that shows the
$this
variable in action:
class Person { var $name; function get_name ( ) { return ...
Get Programming PHP 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.