Objects in php

Object-oriented programming (OOP) opens the door to cleaner designs, easier maintenance, and greater code reuse. The proven value of OOP is such that few today would dare to introduce a language that wasn’t object-oriented. PHP supports many useful features of OOP


Every object-oriented language seems to have a different set of terms for the same old concepts. This section describes the terms that PHP uses, but be warned that in other languages these terms may have other meanings

Creating an Object

It’s much easier to create objects and use them than it is to define object classes, so before we discuss how to define classes, let’s look at creating objects. To create an object of a given class, use the new keyword:

$object = new Class;

Accessing Properties and Methods

Once you have an object, you can use the -> notation to access methods and properties of the object:

$object->propertyname $object->methodname([arg, … ])

For example:

echo "Rasmus is {$rasmus->age} years old.\n"; // property access
$rasmus->birthday(); // method call
$rasmus->setAge(21); // method call with arguments

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:

class classname [ extends baseclass ] [ implements interfacename ,
[interfacename, … ] ]
[ use traitname, [ traitname, … ]; ]
[ visibility $property [ = value ]; … ]

[ function functionname (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, among others), 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 birth day() 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

class Person
 public $name = '';
 function getName()
 return $this->name;
 function setName($newName)
 $this->name = $newName;

Leave a Comment