Objects
object
- oriented programming (OOP) is a style of programming it’s a great way to
build modular, reusable code, letting you create large applications that are
relatively easy to maintain.
The
OOP approach has become very popular with the PHP community in recent years.
What
Is Object - Oriented Programming?
Objects
model the real - world things, processes, and ideas that your application is
designed to handle. An object - oriented application is a set of collaborating
objects that independently handle certain activities.
For
example, when a house is being constructed, the plumbers deal with the pipes,
and the electricians deal with the wires. The plumbers don ’ t need to know
whether the circuit in the bedroom is 10 amps or 20. They need only concern
themselves with their own activities. A general contractor ensures that each
subcontractor is completing the work that needs to be accomplished but isn ’ t
necessarily interested in the particulars of each task.
An
object - oriented approach is similar in that each object hides from the others
the details of its implementation. How it does its job is irrelevant to the
other components of the system. All that matters is the service that the object
is able to provide.
Advantages
of OOP
1. OOP makes it easy
to map business requirements to code modules.
2. A second benefit of
OOP is code reuse.
3. Another OOP
advantage comes from the modularity of classes.
4. Applications
written using OOP are usually relatively easy to understand.
Understanding
Basic OOP Concepts
Classes
A
class called Car , for example, would describe the characteristics and
behaviors common to all cars.
In
the real world, objects have characteristics and behaviors. A car has a color,
a weight, a manufacturer, and a gas tank of a certain volume. Those are its
characteristics. A car can accelerate, stop, signal for a turn, and sound the
horn. Those are its behaviors. Those characteristics and behaviors are common
to all cars. Although different cars may have different colors, all cars have a
color.
Objects
An
object is a specific instance of a class. For example, if you create a Car
class, you might then go on to create an object called myCar that belongs to
the Car class. You could then create a second object, yourCar , also based on
the Car class.
Think
of a class as a blueprint, or factory, for constructing an object. A
class specifies the characteristics that an object will have, but not
necessarily the specific values of those characteristics. Meanwhile, an object
is constructed using the blueprint provided by a class, and its characteristics
have specific values.
Properties
In
OOP terminology, the characteristics of a class or object are
known as its properties . Properties are much like regular variables, in
that they have a name and a value (which can be of any type).
For
example, the Car class might have properties such as color and weight .
Methods
The
behaviors of a class — that is, the actions associated with the class — are
known as its methods . Methods are very similar to functions; in fact,
you define methods in PHP using the function statement. An object ’ s method can
also access the properties of the object.
For
example, an accelerate method of the Car class might check the fuel property to
make sure it has enough fuel to move the car.
The
methods of a class, along with its properties, are collectively known as members
of the class.
Creating
Classes and Objects in PHP
A
class definition consists of the class keyword, followed by the name of the
class, followed by the code that makes up the class, surrounded by curly
brackets ( { } ).
To
create a class, you use PHP ’ s class keyword. Here ’ s a really simple class:
class
Car
{
//
Nothing to see here; move along
}
$benz
= new Car();
$maruthi
= new Car();
print_r(
$benz ); // Displays
“Car Object ( )”
print_r(
$maruthi ); // Displays “Car
Object ( )”
This
code first defines the empty Car class as before, then creates two new
instances of the Car class — that is, two Car objects. It assigns one object to
a variable called $benz , and another to a variable called $maruthi . Note
that, although both objects are based on the same class, they are independent
of each other, and each is stored in its own variable.
Creating
and Using Properties
Understanding Property Visibility
Each
property of a class in PHP can have one of three visibility levels, known as
public, private, and protected:
Public
properties
can be accessed by any code, whether that code is inside or outside the class.
If a property is declared public, its value can be read or changed from
anywhere in your script
Private
properties
of a class can be accessed only by code inside the class. So if you create a property
that ’ s declared private, only methods inside the same class can access its
contents.
(If
you attempt to access the property outside the class, PHP generates a fatal
error.)
Protected
class
properties are a bit like private properties in that they can ’ t be accessed
by code
outside
the class, but there ’ s one subtle difference: any class that inherits from
the class can also access the properties.
Declaring
Properties
To
add a property to a class, first write the keyword public , private , or
protected — depending on the visibility level you want to give to the property
class
MyClass
{
public
$property1; // This is a public property
private
$property2; // This is a private property
protected
$property3; // This is a protected property
}
Accessing
Properties
You
can access the corresponding object ’ s property value from within your calling
code by using the following syntax:
$object->
property;
<
?php
class
Car
{
public
$color;
public
$manufacturer;
}
$benz
= new Car();
$benz->
color = “red”;
$benz->
manufacturer = “Mercedes”;
$maruthi
= new Car();
$maruthi
-> color = “green”;
$maruthi
-> manufacturer = “Suzuki”;
echo
“ <h2> Some properties: </h2> ”;
echo
“ <p> The Benz’s color is “ . $benz-> color . “. </p> ”;
echo
“ <p> The Maruthi’s manufacturer is “ . $maruthi-> manufacturer . “.
</p> ”;
echo
“ <h2> The \$benz Object: </h2> <pre> ”;
echo
“ </pre> ”;
echo
“ <h2> The \$maruthi Object: </h2> <pre> ”;
print_r(
$maruthi );
echo
“ </pre> ”;
?>
Static
Properties
You
can also create static class properties in a similar way, by adding the static
keyword just before the property name:
class
MyClass
{
public
static $myProperty;
}
Static
members of a class are independent of any particular object derived from that
class. To access a static property, you write the class name, followed by two
colons ( :: ), followed by the property name (preceded by a $ symbol):
MyClass::$myProperty
= 123;
Class
Constants
To
define a class constant, use the keyword const , as follows:
class
MyClass
{
const
MYCONST = 123;
}
Like
static properties, you access class constants via the class name and the ::
operator:
echo
MyClass::MYCONST;
Working with Methods
Method Visibility
Methods
have 3 visibility levels: public, private, and protected.
If
a method is declared public, any code outside the class definition can also
potentially call the method.
If a method is declared private, only other methods within the same class can call it.
Finally, a protected method can be called by other methods
in the class, or in a class that inherits from the class.
Creating
a Method
To
add a method to a class, use the public , private , or protected keyword, then
the function
keyword,
followed by the method name, followed by parentheses. You then include the
method ’ s code within curly braces:
class
MyClass
{
public
function aMethod()
{
//
(do stuff here)
}
}
Calling
Methods
To
call an object ’ s method, simply write the object ’ s name, then the same
arrow used for accessing properties ( -> ), then the method name followed by
parentheses:
$object->
method();
class
MyClass
{
public
function hello()
{
echo
“Hello, World!”;
}
}
$obj
= new MyClass;
$obj->
hello(); // Displays
“Hello, World!”
Adding
Parameters and Returning Values
You
add parameters and return values in much the same way as with functions.
public
function aMethod( $param1, $param2 )
{
//
(do stuff here)
return
true;
}
Accessing
Object Properties from Methods
To
access an object ’ s property from within a method of the same object, you use
the special variable name $this , as follows:
$this->
property;
Example:
class
MyClass
{
public
$greeting = “Hello, World!”;
public
function hello()
{
echo
$this-> greeting;
}
}
$obj
= new MyClass;
$obj->
hello(); // Displays “Hello, World!”
Static
Methods
To
make a method static, add the static keyword before the function keyword in the
method definition:
class
MyClass
{
public
static function staticMethod()
{
//
(do stuff here)
}
}
To
call a static method, write the class name, followed by two colons, followed by
the method name and the arguments (if any) in parentheses:
MyClass::staticMethod();
Static
properties, static methods are useful when you want to add some functionality
that ’ s related to a class, but that doesn’t need to work with an actual
object created from the class.
Making
Your Classes Self - Contained with Encapsulation
One
of the strengths of OOP is the concept of encapsulation . This means that a
class ’ s internal data should be protected from being directly manipulated
from outside, and that the details of the class ’ s implementation — such as
how it stores values or manipulates data — should be hidden from the outside
world. By doing this, you gain two advantages:
1. You can change your
class ’ s implementation details at any time without affecting code that uses
the class
2. You can trust the
state of an object to be valid and to make sense
class
Account
{
private
$_totalBalance = 0;
public
function makeDeposit( $amount )
{
$this->
totalBalance += $amount;
}
public
function makeWithdrawal( $amount )
{
if
( $amount < $this-> totalBalance )
{
$this->
totalBalance -= $amount;
}
else
{
die(
“Insufficient funds < br / > ” );
}
}
public
function getTotalBalance()
{
return
$this-> totalBalance;
}
}
$a
= new Account;
$a->
makeDeposit( 500 );
$a->
makeWithdrawal( 100 );
echo
$a-> getTotalBalance() . “ <br/> ”; //
Displays “400”;
$a->
makeWithdrawal( 1000 ); //
Displays “Insufficient funds”
Object Overloading with __get(), __set(),
and __call()
PHP can intercept attempts to read or write
an object's properties, or call its methods. PHP can create three
"magic" methods that you can use to intercept property and method
accesses:
__get() is called whenever the calling code
attempts to read an invisible property of the object
__set() is called whenever the calling code
attempts to write to an invisible property of
the object
__call() is called whenever the calling code
attempts to call an invisible method of the object
What is meant by “ invisible ” ?
In this context, invisible means that the property or method isn ’ t visible to the calling code. Usually this means that the property or method simply doesn ’ t exist in the class, but it can also mean that the property or method is either private or protected, and hence isn ’ t accessible to code outside the class.
To intercept attempts to read an invisible
property, you create a method called __get() within your class. Your __get()
method should expect a single argument: the name of the requested property.
It should then return a value; this value
in turn gets passed back to the calling code as the retrieved property value.
<?php
class Car
{
public function __get( $propertyName )
{
echo “The value of ‘$propertyName’ was
requested <br/> ”;
return “blue”;
}
}
$car = new Car;
$x = $car-> color; // Displays “The value of ‘color’ was
requested”
echo “The car’s color is $x <br/> ”; // Displays “The car’s color is blue”
?>
In this example, the Car class
contains no actual properties, but it does contain a _get() method. This method
simply displays the value of the requested property name, and returns the value
“blue”. The rest of the script creates a new Car object, and attempts to
retrieve the nonexistent property $car - > color , storing the result in a new
variable, $x . Doing this triggers the Car object’s _get() method, which
displays the requested property name ( “ color “ ) and returns the literal
string “blue” . This string is then passed back to the calling code and stored
in $x , as shown by the last line of code.
Using Inheritance to Extend the
Power of Objects
Inheritance, Using this technique, you can
create classes — known as child classes — that are based on another
class: the parent class . A child class inherits all the properties and
methods of its parent, and it can also add additional properties and methods.
Imagine that you ’ re creating a
program to deal with various regular shapes, such as circles, squares, equilateral
triangles, and so on. You want to create a Shape class that can store
information such as number of sides, side length, radius, and color, and that
can calculate values such as the shape ’ s area and perimeter. However, not all
shapes are the same. Circles don ’ t really have a clearly defined number of sides,
and you calculate an equilateral triangle ’ s area using a different formula
than for a square. So if you wanted to handle all types of regular shapes in a
single Shape class, your class ’ s code would get quite complicated.
By using inheritance, however, you can
break the problem down into simpler steps. First, you create a parent Shape
class that contains just those properties and methods that are common to all
shapes. Then, you can create child classes such as Circle , Square , and
Triangle that inherit from the Shape class.
To create a child class that ’ s based on a
parent class, you use the extends keyword, as follows:
class Shape
{
// (General Shape properties and methods
here)
}
class Circle extends Shape
{
// (Circle-specific properties and methods
here)
}
It creates a parent Shape class, holding
properties and methods common to all shapes, then creates two child classes
based on Shape — Circle and Square — that contain properties and methods
related to circles and squares, respectively.
<?php
class Shape
{
private $_color ="black";
private $_filled = false;
public function getColor()
{
return $this->_color;
}
public function setColor($color)
{
$this->_color = $color;
}
public function isFilled()
{
return $this->_filled;
}
public function fill()
{
$this->_filled = true;
}
public function makeHollow()
{
$this->_filled = false;
}
}
class Circle extends Shape
{
private $_radius = 0;
public function getRadius()
{
return $this->_radius;
}
public function setRadius($radius)
{
$this->_radius = $radius;
}
public function getArea()
{
return M_PI * pow($this->_radius, 2);
}
}
class Square extends Shape
{
private $_sideLength = 0;
public function getSideLength()
{
return $this->_sideLength;
public function setSideLength($length)
{
$this->_sideLength = $length;
}
public function getArea()
{
return pow($this->_sideLength, 2);
}
}
$myCircle = new Circle;
$myCircle->setColor("red");
$myCircle->fill();
$myCircle->setRadius(4);
echo "My Circle \n";
echo "My circle has a radius of".
$myCircle->getRadius().".\n";
echo "It is".
$myCircle->getColor()."and it is". ($myCircle->isFilled()
?"filled":"hollow").".\n";
echo "The area of my circle is:".
$myCircle->getArea().".\n";
$mySquare = new Square;
$mySquare->setColor("green");
$mySquare->makeHollow();
$mySquare->setSideLength(3);
echo "My Square \n";
echo "My square has a side length
of". $mySquare->getSideLength(). ".\n";
echo "It is".
$mySquare->getColor()."and it is". ($mySquare->isFilled()?"filled":"hollow").".
</p>";
echo "The area of my square is:".
$mySquare->getArea().".\n";
?>
Overriding Methods in the Parent Class
To create a child class whose methods are
different from the corresponding methods in the parent class, override methods
from parent. PHP can override a parent class's method in the child class. To do
this, simply create a method with the same name in the child class.
Then, when that method name is called for
an object of the child class, the child class's method is run instead of the
parent class's method:
<?php
class Fruit {
public function peel() {
echo "I'm peeling the fruit...\n";
}
public function slice() {
echo "I'm slicing the fruit...\n";
}
public function eat() {
echo "I'm eating the fruit. Yummy!\n";
}
public function consume() {
$this->peel();
$this->slice();
$this->eat();
}
}
class Grape extends Fruit {
public function peel() {
echo "No need to peel a grape!\n";
}
public function slice() {
echo "No need to slice a grape!\n";
}
echo "Consuming an apple...";
$apple = new Fruit;
$apple->consume();
echo "Consuming a grape...";
$grape = new Grape;
$grape->consume();
?>
Preserving the Functionality of the Parent
Class
To override the method of a parent class in
your child class, and also use some of the functionality that is in the parent
class's method.
You can do this by calling the parent
class's overridden method from within the child class's method.
To call an overridden method, you write
parent:: before the method name:
parent::someMethod();
<?php
class Fruit {
public function peel() {
echo "I'm peeling the fruit...\n";
}
public function slice() {
echo "I'm slicing the fruit...\n";
}
public function eat() {
echo "I'm eating the fruit. Yummy!\n";
}
public function consume() {
$this->peel();
$this->slice();
$this->eat();
}
}
class Banana extends Fruit {
public function consume() {
echo "I'm breaking off a banana...\n";
parent::consume();
}
$banana = new Banana;
$banana->consume();
?>
Blocking Inheritance and Overrides with
Final Classes and Methods
To lock down a class so that it can't be
inherited from. To lock down one or more methods inside a class so that they
can't be overridden in a child class. By doing this, you know that your class
or methods within your class will always behave in exactly the same way. You
can add the keyword final before a class or method definition to lock down that
class or method.
You can add the keyword final before a
class or method definition to lock down that class or method.
<?php
final class HandsOffThisClass {
public $someProperty = 123;
public function someMethod() {
echo "A method";
}
}
// Generates an error:
//"Class ChildClass may not inherit from final class
(HandsOffThisClass)"
class ChildClass extends HandsOffThisClass {
}
?>
Using Abstract Classes and Methods
When can define a class abstract using the
abstract keyword. An class which is defined as abstract cannot be instantiated.
Following are some important points about
abstract class and method:
1. An abstract class
can have methods and properties just like any other normal class.
2. An abstract class
cannot be instantiated, hence we need to create a child class which extends it,
then we can create object of the child class.
3. If a class has even
a single abstract method then the class should also be abstract.
4. An abstract method
is just the declaration, where we provide name of the method and argument,
while the body part is empty.
Creating an abstract Class
To declare a class abstract, we need to use
the abstract keyword before the name of the class.
Let's take an example:
<?php
// abstract class
abstract class Vehicle {
// protected variable
protected $name;
// non-abstract public function start
public function start() {
echo $this->name. " - Engine start...<br/>";
}
// non-abstract public function stop
public function stop() {
echo $this->name. " - Engine stop...<br/>";
}
// non-abstract public function setName
public function setName($name) {
$this->name = $name;
}
// abstract function mileage
abstract public function mileage() {
}
}
?>
Working with Interfaces
An interface allows you to specify a
contract that a class must implement. To define an interface, you use the
interface keyword .
An interface consists of methods that
contain no implementation. In other words, all methods of the interface are
abstract methods. An interface can also include constants.
When you define a class (child class) that
reuses properties and methods of another class (parent class), the child class
extends the parent class.
However, for interfaces, we say that a
class implements an interface. A class can inherit from one class only. However,
it can implement multiple interfaces. To define a class that implements an
interface, you use the implements keyword as follows:
<?php
interface MyInterface
{
const
CONSTANT_NAME = 1;
public
function methodName();
}
class MyClass implements MyInterface
{
public
function methodName()
{
//
...
}
}
When a class implements an interface, it’s
called a concrete class. The concrete class needs to implement all the
methods of the interface.
Why should you use PHP interfaces?
1. By implementing an
interface, the object’s caller needs to care only about the object’s interface,
not implementations of the object’s methods. Therefore you can change the
implementations without affecting the caller of the interface.
2. An interface allows
unrelated classes to implement the same set of methods, regardless of their
positions in the class inheritance hierarchy.
3. An interface
enables you to model multiple inheritances because a class can implement more
than one interface.
Constructors and Destructors
An object ’ s constructor method is called
just after the object is created, and its destructor method is called just
before the object is freed from memory.
Setting Up New Objects with Constructors
To create a constructor, simply add a method
with the special name _construct() to your class.
class Person
{
private $_firstName;
private $_lastName;
private $_age;
public function __construct($firstName,
$lastName, $age )
{
$this-> firstName = $firstName;
$this-> lastName = $lastName;
$this-> age = $age;
}
public function showDetails()
{
echo “$this-> firstName $this->
lastName, age $this-> age <br >
”;
}
}
$p = new Person( “Harry”, “Walters”, 28 );
$p- > showDetails(); // Displays “Harry
Walters, age 28”
Cleaning Up Objects with Destructors
For example, if an object has a few files
open, or contains data that should be written to a database, it ’ s a good idea
to close the files or write the data before the object disappears.
You create destructor methods in the same
way as constructors, except that you use _destruct() rather than _construct() :
function __destruct()
{
// (Clean up here)
}
A destructor can ’ t accept arguments
class Person
{
public function save()
{
echo “Saving this object to the database...
<br /> ”;
}
public function __destruct()
{
$this-> save();
}
}
$p = new Person; // A new Person object is created and stored in the variable $p
unset( $p );
$p2 = new Person;
die( “Something’s gone horribly wrong!
<br /> ”);
Output
Saving this object to the database...
Something ’ s gone horribly wrong!
Saving this object to the database...
//$p is removed from memory using the built - in
unset() function .Doing this removes the only reference to the Person object,
so it ’ s deleted. But just before it ’ s removed, its _destruct() method is
called, displaying the message “Saving this object to the database...”
Next the code creates another Person object, storing it
in the variable $p2 . Finally, the code raises an error using the built - in
die() function, which causes the script to end with a “Something ’ s gone horribly
wrong!” message. Just before the script finally terminates, however, the object
’ s destructor is called, displaying the “Saving this object to the
database...” message.
Automatically Loading Class Files
With autoloading, you create an _autoload()
function somewhere in your script. This function should accept a class name as
an argument. Then, whenever another part of your script attempts to create a
new object from a nonexistent class, _autoload() is automatically called,
passing in the class name. This gives your _autoload() function a chance to
find and include the class file, thereby allowing the PHP engine to carry on
and create the object.
Here ’ s an example _autoload() function:
function __autoload( $className )
{
$className = str_replace ( “..”, “”,
$className );
require_once( “classes/$className.php” );
}
For example, imagine the same script
contained the following code:
$p = new Person;
When the PHP engine encounters the new Person
construct, it looks to see if the Person class has been defined. If not, it
calls the previously defined _autoload() function. This in turn includes and
runs the file Person.php inside the classes folder, which creates the class and
allows the new Person object to be created.
If the PHP engine can ’ t find an
_autoload() function, or if your _autoload() function fails to load the Person
class, the script exits with a “Class ‘ Person ’ not found” error.
Storing Objects as Strings
Objects that you create in PHP are stored
as binary data in memory.
PHP provides two functions to help you with
this:
Method Description
serialize() converts
an object - properties, methods, and all - into a string of text
unserialize() takes a string created by serialize() and turns it back
into a usable object
The
following example shows these two functions in action:
<?php
class Person
{
public $age;
}
$harry = new Person();
$harry- > age = 28;
$harryString = serialize( $harry );
echo “Harry is now serialized in the
following string: ‘$harryString’ < br / > ”;
echo “Converting ‘$harryString’ back to an
object... < br / > ”;
$obj = unserialize( $harryString );
echo “Harry’s age is: $obj-> age < br
/ > ”;
?>
Output:
Harry is now serialized in the following
string: ‘O:6:”Person”:1:{s:3:”age”;i:28;}’
Converting
‘O:6:”Person”:1:{s:3:”age”;i:28;}’ back to an object...
Harry’s age is: 28
Previous Topic(Functions) NextTopic(Handling HTML Forms PHP)
No comments:
Post a Comment