Você está na página 1de 18

Object Oriented Programming

Introduction to Object-Oriented Programming Using PHP.This page will describes the term `objectoriented programming`.let's start with few basic concepts before you can begin writing any code.
Object-oriented programming is a method of programming based on a hierarchy of classes, and welldefined objects.
Brief overview of object-oriented concepts and terminology:

Object.
Class.
Inheritance.
Interface.
Package.

Unied Modeling Language(UML)


UML stands for Unied Modeling Language.UML is used to manage large and complex systems.
With UML you can:

Manage project complexity.


create database schema.
Produce reports.

Types of UML Diagrams:


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

Class Diagrams
Package Diagrams
Object Diagrams
Use Case Diagrams
Sequence Diagrams
Collaboration Diagrams
State chart Diagrams
Activity Diagrams
Component Diagrams
Deployment Diagrams

Advantages of object oriented programming:

Code Re-usability(Polymorphism,Interfaces): In OOPs objects created in one program can be


reused in different programs.
Code extensibility: for addding new features or modifying existing objects can be solved by
introducing new objects.
Catch errors at compile time rather than at runtime.
Maintainability :objects can be maintained separately, so u can easily fix errors.
Imrove error handling:We can use exceptions to improve error handling.
Modularity: can create seperate Modules.
Modifiability:it is easy to make minor changes in some classes as Changes inside a class do not
affect any other part of a program.

Class in OOP
class is like a blueprint/template in OOPs, and this template is used to create objects.The collection of
properties & behavior of an object is also called as class.
A class contains properties, fields, data members, attributes.
Example:
Car is an object , cars is a class
public class cars
{
//
}
According to the sample given below we can say that the cars object, named object_car, has created out
of the cars class.
cars object_car = new cars();
Object in Object oriented programming
object is an instance of a class.An object is an entity that has attributes, behavior, and identity. Objects
are members of a class.
Objects are accessed, created or deleted during program run-time.
Declaration of an Object in OOPs
ClassName objectName=new ClassName();

Example:
Car objCar= new Car();
Attribute in OOPs: Attributes define the characteristics of a class. In Class Program attribute can be a
string or it can be a integer.
Behavior in OOPS: Every object has behavior.
Identity in OOPS: Each time an object is created the object identity is been defined.
What is the relation between Classes and Objects
Class is a definition, while object is a instance of the class created.
class is like a blueprint/template in OOPs, and this template is used to create objects.The collection of
properties & behavior of an object is also called as class.
A class contains properties, fields, data members, attributes.
Example:Car is an object , cars is a class
public class cars
{
//
}

According to the sample given below we can say that the cars object, named object_car, has created out
of the cars class.
cars object_car = new cars();
object is an instance of a class.An object is an entity that has attributes, behavior, and identity. Objects
are members of a class.
Objects are accessed, created or deleted during program run-time.
Declaration of an Object in OOPs
ClassName objectName=new ClassName();
Example:
Car objCar= new Car();

Attribute in OOPs: Attributes define the characteristics of a class. In Class Program attribute can be a
string or it can be a integer.
Behavior in OOPS: Every object has behavior.
Identity in OOPS: Each time an object is created the object identity is been defined.
roperties of Object Oriented Systems:

support inheritance
provides encapsulation of data
provides extensibility of existing data types and classes
provide support for complex data types
Inheritance-one class inherite the property of another class..
Aggregation-.is a part whole relationship.
Association.:is a relationship between 1 or more instances of a class.
In this tutorial ,I will explain about abstract class in PHP, how to declare and use of an
abstract class.
Abstract Class:
It may contain one or more abstract methods.abstract classes may not be instantiated.The
child classes which inherits the property of abstract base class, must define all the methods
declared as abstract.
Any class that contains at least one abstract method must also be abstract.
if the abstract method is defined as protected, the function implementation must be defined as
either protected or public, but not private.

Example:
<?php
abstract class AbstractClass
{
abstract protected function getValue();
abstract protected function setValue($val);
public function Display() {
print $this->getValue() . "\n";
}
}

class ChildClass1 extends AbstractClass


{

protected function getValue() {

return "ChildClass1";

public function setValue($val) {

return "ChildClass{$val}";

}
}

class ChildClass2 extends AbstractClass


{

public function getValue() {

return "ChildClass2";

public function setValue($val) {

return "ChildClass{$val}";

}
}

$class1 = new ChildClass1;


$class1->Display();
echo "<br>";
echo $class1->setValue('1') ."\n";
echo "<br>";
$class2 = new ChildClass2;
$class2->Display();
echo "<br>";
echo $class2->setValue('2') ."\n";
?>
Encapsulation:
The wrapping of data and function together in a single unit(class) is called encapsulation.
In PHP 4 objects were little more than arrays.In PHP 5 you get much more control by visibility,
interfaces,and more.

PHP5 provides data-hiding capabilities with public, protected, and private data attributes and methods:
Public : A public variable or method can be accessed directly by any user of the class.
Protected : A protected variable or method cannot be accessed by users of the class but can be
accessed inside a subclass that inherits from the class.
Private: private variable or method can only be accessed internally from the class in which it is
defined.
E.g.:
class is a protective wrapper which binds data and methods together,they can be accessed only though
object of that class.

Example:

<?php
class Shape {
private static $_circle;
public function Circle( ) {
if( $this->_circle == null ) {
$this->_circle = new Circle();
}
return $this->_circle;
}

}
class Circle {
private $_radius;
public function __construct() {
$this->_radius = "10";
}
public function GetRadius() {
return $this->_radius;
}
}
$shape= new Shape();
echo $shape->Circle()->GetRadius();
?>
Abstract Class:
To define a class as Abstract, the keyword abstract is to be used e.g. abstract class ClassName { }

In abstract class at least one method must be abstract.


we can create object of abstract class.
Abstract classes may not be instantiated.
The child classes which inherits the property of abstract base class, must define all the
methods declared as abstract.
Any class that contains at least one abstract method must also be abstract.
If the abstract method is defined as protected, the function implementation must be defined as
either protected or public, but not private.
Abstract class can contain variables and concrete methods.
A class can Inherit only one Abstract class and Multiple inheritance is not possible for Abstract
class.

Example:
<?php
abstract class AbstractClass
{
abstract protected function getValue();
abstract protected function setValue($val);
public function Display() {
print $this->getValue() . "\n";
}
}
class ChildClass1 extends AbstractClass
{
protected function getValue() {
return "ChildClass1";
}

public function setValue($val) {


return "ChildClass{$val}";
}

class ChildClass2 extends AbstractClass


{
public function getValue() {
return "ChildClass2";
}
public function setValue($val) {
return "ChildClass{$val}";
}
}
$class1 = new ChildClass1;
$class1->Display();
echo "<br>";
echo $class1->setValue('1') ."\n";
echo "<br>";
$class2 = new ChildClass2;
$class2->Display();
echo "<br>";
echo $class2->setValue('2') ."\n";
?>
Interfaces:

In interface all the method must be abstract(only define).


All methods declared in an interface must be public.

Interfaces cannot contain variables and concrete methods except constants.


A class can implement many interfaces and Multiple interface inheritance is possible.
To extend from an Interface, keyword implements is used.

Example:
interface Shape
{
function getShape();
}
class Circle implements Shape{
public function getShape() {
return "This is Shape of the Circle\n";
}
}
class MultiInher {
public function read(Shape $s) {
$shape = $s->getShape();
//
echo $shape;
}
}
$c = new Circle();
$m = new MultiInher();
$m->read($c);
Abstract Class:
To define a class as Abstract, the keyword abstract is to be used e.g. abstract class ClassName { }

In abstract class at least one method must be abstract.


we can create object of abstract class.
Abstract classes may not be instantiated.
The child classes which inherits the property of abstract base class, must define all the
methods declared as abstract.
Any class that contains at least one abstract method must also be abstract.
If the abstract method is defined as protected, the function implementation must be defined as
either protected or public, but not private.
Abstract class can contain variables and concrete methods.
A class can Inherit only one Abstract class and Multiple inheritance is not possible for Abstract
class.

Example:
<?php
abstract class AbstractClass

{
abstract protected function getValue();
abstract protected function setValue($val);
public function Display() {
print $this->getValue() . "\n";
}
}
class ChildClass1 extends AbstractClass
{
protected function getValue() {
return "ChildClass1";
}
public function setValue($val) {
return "ChildClass{$val}";
}
}
class ChildClass2 extends AbstractClass
{
public function getValue() {
return "ChildClass2";
}
public function setValue($val) {
return "ChildClass{$val}";
}
}
$class1 = new ChildClass1;
$class1->Display();
echo "<br>";
echo $class1->setValue('1') ."\n";
echo "<br>";
$class2 = new ChildClass2;
$class2->Display();
echo "<br>";
echo $class2->setValue('2') ."\n";
?>
Abstract Class:

To define a class as Abstract, the keyword abstract is to be used.


In abstract class at least one method must be abstract.
we can create object of abstract class.
abstract classes may not be instantiated.

The child classes which inherits the property of abstract base class, must define all the
methods declared as abstract.
Any class that contains at least one abstract method must also be abstract.
If the abstract method is defined as protected, the function implementation must be defined as
either protected or public, but not private.
Abstract class can contain variables and concrete methods.
A class can Inherit only one Abstract class and Multiple inheritance is not possible for Abstract
class.

Interfaces:

In interface all the method must be abstract.


All methods declared in an interface must be public.
Interfaces cannot contain variables and concrete methods except constants.
A class can implement many interfaces and Multiple interface inheritance is possible.
To extend from an Interface, keyword implements is used.

Static Keyword:
In this Article,I will explain how to use Static Keyword in PHP5.

To implement static keyword functionality to the attributes or the methods will have to be
prefix with static keyword.
Static properties or methods can be accessible without needing an instantiation of the class.
A property declared as static can not be accessed with an instantiated class object.
$this is not available inside the method declared as static.
Static properties cannot be accessed using the arrow operator ->.
Static properties can be accessed using the Scope Resolution Operator (::) operator.
ClassName::$staticvar= $value;

Example:
<?php
class Box
{
static private $color;
function __construct($value)
{
if($value != "")
{
Box::$color = $value;
}
$this->getColor();
}
public function getColor ()
{
echo Box::$color;

}
}
$a = new Box("RED");
$a = new Box("GREEN");
$a = new Box("");
?>
OUTPUT:
RED
GREEN
GREEN
Static Keyword:
In this Article,I will explain how to use Static Keyword in PHP5.

To implement static keyword functionality to the attributes or the methods will have to be
prefix with static keyword.
Static properties or methods can be accessible without needing an instantiation of the class.
A property declared as static can not be accessed with an instantiated class object.
$this is not available inside the method declared as static.
Static properties cannot be accessed using the arrow operator ->.
Static properties can be accessed using the Scope Resolution Operator (::) operator.
ClassName::$staticvar= $value;

Example:

<?php
class Box
{
static private $color;
function __construct($value)
{
if($value != "")
{
Box::$color = $value;
}
$this->getColor();
}
public function getColor ()
{
echo Box::$color;
}
}

$a = new Box("RED");
$a = new Box("GREEN");
$a = new Box("");
?>
OUTPUT:
RED
GREEN
GREENStatic Methods and Properties:

In this Article,I will explain how to use Static properties or methods in PHP5.

To implement static keyword functionality to the attributes or the methods will have to be
prefix with static keyword.
Static properties or methods can be accessible without needing an instantiation of the class.
A property declared as static can not be accessed with an instantiated class object.
$this is not available inside the method declared as static.
Static properties cannot be accessed using the arrow operator ->.
Static properties can be accessed using the Scope Resolution Operator (::) operator.

ClassName::$staticvar= $value;

Example:
<?php
class Box
{
static private $color;
function __construct($value)
{
if($value != "")
{
Box::$color = $value;
}
$this->getColor();
}
public function getColor()
{
echo Box::$color ;
}
static public function StaticMethod() {

echo self::$color;

}
$a = new Box("RED");
Box::StaticMethod();
$a = new Box("GREEN");
$a = new Box("");
?>

OUTPUT:
RED
RED
GREEN
GREENConstructor:

PHP 5 allows developers to declare constructor methods for classes.Classes call constructor method on
each newly-created object.
function __construct() {
//
}
Example:

<?php
class MainClass {
function __construct() {
echo "In MainClass constructor\n";
}
}

class ChildClass extends MainClass {


function __construct() {
parent::__construct();
echo "In SubClass constructor\n";
}
}

$obj = new MainClass();


$obj = new SubClass();
?>

Note: If PHP 5 cannot find a __construct() function for a given class, it will search for the old
constructor function, by the name of the class.
Destructor:
The destructor method will be called as soon as Classes destroy the object.

function __destruct() {
//
}
Example:

<?php
class MainClass {
function __construct() {
echo "In MainClass constructor\n";
}
function __destruct() {
print "Destroying \n";
}
}
class ChildClass extends MainClass {
function __construct() {
parent::__construct();
echo "In SubClass constructor\n";
}
}
$obj = new MainClass();
$obj = new SubClass();
?>
Note:The destructor method will be called even if script execution is stopped using exit().
Access modifier:
OOP provides data-hiding capabilities with public, protected, and private data attributes and methods:
Public : A public variable or method can be accessed directly by any user of the class.
Protected : A protected variable or method cannot be accessed by users of the class but can be
accessed inside a subclass that inherits from the class.
Private:A private variable or method can only be accessed internally from the class in which it is
defined.

Serialization/UnSerialization:

Generates a storable representation of a value.


serialize() returns a string containing a byte-stream representation of any value that can be
stored in PHP.
unserialize() can use this string to recreate the original variable values.
This process makes a storable representation of a value that is useful for storing or passing
PHP values.
To make the serialized string into a PHP value again, use unserialize().

Before starting your serialization process, PHP will execute the __sleep function automatically. This is a
magic function or method.
Before starting your unserialization process, PHP will execute the __wakeup function automatically.
This is a magic function or method.
What can you Serialize and Unserialize?

Variables
Arrays
Objects

What cannot you Serialize and Unserialize?

Resource-type

Example:
//BaseClass.php
<?php
class BaseClass {
public $var = 100;
public function show() {
echo $this->var;
}
}
// test1.php:
include("BaseClass.php");
$a = new A;
$v = serialize($a);
file_put_contents('store_in_var', $v);
// page2.php:
include("BaseClass.php");
$v = file_get_contents('store_in_var');

$a = unserialize($v);
$a->show();
?>
In the Case if you want to store entire array into database then with serialze() it would be useful to
store an entire array in a field in a database.
You can pass an array to the function, and it will return a string that is essentially the string.
You can then unserialize() it to obtain the full array once again.
example:
<?php
$str_array = array( "Rajesh Sharma", "Rajesh", "RajeshS" );
$serialized_str = serialize($str_array);
echo $serialized_str;
?>
This will output a:3:{i:0;s:14:"Rajesh Sharma";i:1;s:6:"Rajesh";i:2;s:7:"RajeshS";}
so you can store entire array in a field in a database.
<?php
$str_array = array( "Rajesh Sharma", "Rajesh", "RajeshS" );
$serialized_str = serialize($str_array);
print_r(unserialize($serialized_str));
?>
This will output a Array ( [0] => Rajesh Sharma[1] => Rajesh [2] => RajeshS ).
Inheritance in OOP :
In this tutorial we will study about Inheritance.

Inheritance is a mechanism of extending an existing class.


In Inheritance child class inherits all the functionality of Parent Class.

For example, when you extend a class, the subclass inherits all of the public and protected methods
from the parent class. Unless a class overrides those methods.
<?php
class BaseClass
{
public function GetValue($string)
{
echo 'BaseClass:'. $string ;
}
public function setValue($string)
{
echo $string;

}
}
class ChildClass extends BaseClass
{
public function GetValue($string)
{
echo 'ChildClass:'. $string ;
}
}
$b = new BaseClass();
$c = new ChildClass();
$b->GetValue('Rajesh Test'); // Output: 'BaseClass: Rajesh Test'
$b->setValue('Rajesh Test'); // Output: 'Rajesh Test'
$c->GetValue('Rajesh Tutorials'); // Output:'ChildClass: Rajesh Tutorials'
$c->setValue('Rajesh Test'); // Output: 'Rajesh Test'
?>
Encapsulation:
The wrapping of data and function together in a single unit(class) is called encapsulation.
In PHP 4 objects were little more than arrays.In PHP 5 you get much more control by visibility,
interfaces,and more.
PHP5 provides data-hiding capabilities with public, protected, and private data attributes and methods:
Public : A public variable or method can be accessed directly by any user of the class.
Protected : A protected variable or method cannot be accessed by users of the class but can be
accessed inside a subclass that inherits from the class.
Private: private variable or method can only be accessed internally from the class in which it is
defined.
E.g.:
class is a protective wrapper which binds data and methods together,they can be accessed only though
object of that class.
Example:
<?php
class Shape {
private static $_circle;
public function Circle( ) {

if( $this->_circle == null ) {


$this->_circle = new Circle();
}
return $this->_circle;
}
}
class Circle {
private $_radius;
public function __construct() {
$this->_radius = "10";
}
public function GetRadius() {
return $this->_radius;
}
}
$shape= new Shape();
echo $shape->Circle()->GetRadius();
?> Polymorphism in OOP:

In this tutorial we will study about polymorphism.

Polymorphism in PHP5 : To allow a class member to perform diffrent tasks.


polymorphism where the function to be called is detected based on the class object calling it at
runtime.

Example:
<?
class Person
{
public function Talk()
{
echo "English";
}
}
class Language extends Person
{

public function Talk()


{
echo "French";
}

}
function CallMethod(Person $p)
{
$p->Talk();
}
$l = new Language();
CallMethod($l);
?>

Output:
French;

Você também pode gostar