Sie sind auf Seite 1von 52

OOP IN PHP

OOP = Object Oriented Programming Nature of OOP Class Object Attribute Method Abstraction Encapsulation information hiding Polymorphism Inheritance

Class
Definition of a Class A class is user defined data type that contains attributes or data members; and methods which work on the data members. (You will learn more about data members and methods in following tutorials. This tutorial focuses only on learning how to create a Class in PHP5)

Class

To create a class, you need to use the keyword class followed by the name of the class. The name of the class should be meaningful to exist within the system (See note on naming a class towards the end of the article). The body of the class is placed between two curly brackets within which you declare class data members/variables and class methods.

Example creat a class


class Customer { private $first_name, $last_name; public function setData($first_name, $last_name) { $this->first_name = $first_name; $this>last_name = $last_name; } public function printData() { echo $this->first_name . " : " . $this>last_name; } }

Naming Conventions
Naming Convention for Class: As a general Object Oriented Programming practice, it is better to name the class as the name of the real world entity rather than giving it a fictitious name. For example, to represent a customer in your OOAD model; you should name the class as Customer instead of Person or something else. Naming Conventions for Methods: The same rule applies for class methods. The name of the method should tell you what action or functionality it will perform. E.g. getData() tells you that it will accept some data as input and printData() tells you that it will printData(). So ask yourself what you would name a method which stores data in the database. If you said storeDataInDB() you were right. Look at the manner in which the method storeDataInDB() has been named. The first character of the first word of the method is lower case i.e. store. For rest of the words in the function viz Data/In/DB have been named as first character Uppercase and the remaining characters of the words as lower case i.e. Data In DB. Therefore it becomes storeDataInDB() Naming Convention for Attributes: Attributes of a class should be named on the basis of the data that they hold. You should always give meaningful names to your attributes. For attributes you should split the words with an underscore (_) i.e. $first_name, $last_name, etc.

Object
Definition of an Object An object is a living instance of a class. This means that an object is created from the definition of the class and is loaded in memory.

Create a PHP5 Class Object To create an object of a PHP5 class we use the keyword new $obj_name = new ClassName();

Example creat object


class Customer { private $first_name, $last_name;
public function getData($first_name, $last_name) { $this->first_name = $first_name; $this->last_name = $last_name; }

public function printData() { echo $this->first_name . " : " . $this>last_name; } } $c1 = new Customer(); $c2 = new Customer();

Attributes

Definition of an class attribute An attribute is also know as data members and is used to hold data of a class. The data that it holds are specific to the nature of the class in which it has been defined. For example, a Customer class would hold data related to a customer, an Order class would hold data related a an order.

Example attribute
class Student { public $first_name; public $last_name; public $date_of_birth; public $address; private $telephone; private $cardID; protected $faculty; }

Example creat more object of class


//creating an object $s1 of Student class and assigning data

$s1 = new Student(); $s1->first_name = "Sunil"; $s1->last_name = "Bhatia"; $s1->date_of_birth = "01/01/1900"; $s1->address = "India"; $s1->telephone = "9999999999"; //creating an object $s2 of Student class and assigning data $s2 = new Student(); $s2->first_name = "Vishal"; $s2->last_name = "Thakur"; $s2->date_of_birth = "01/01/1910"; $s2->address = "USA"; $s2->telephone = "8888888888";

Method
Definition of an class method A class method/functions is the behavior/functionality of a class. they provide the necessary code for the class in which it is defined. Examples could be a saveCustomer() method in the class Customer or a printDocument() in the Document class. Methods can also be declared as either public, protected or private.

Example creat a method in class


class Customer { private $name; public function setName($name) { if(trim($name) != "") { $this->name = $name; return true; } else { return false; } } } $c1 = new Customer(); $c1->setName("Sunil Bhatia");

//now we want to access to $name??

Lets look at an example of accessor and mutator methods below:


class Customer { private $name; //mutator method public function setName($name) { if(trim($name) != "") { $this->name = $name; return true; } else { return false; } } //accessor method public getName() { return $this->name; } } $c1 = new Customer(); $c1->setName("Sunil Bhatia"); echo $c1->getName();

Constructor
Definition of a Constructor A constructor is a special function of a class that is automatically executed whenever an object of a class gets instantiated. What does this all mean? Lets revisit that definition in more simple terms. A constructor is a special function this means that a constructor is a function; but its special. But, why is it special? Its special because it is automatically executed or called when an object of a class is created. Why do we need a Constructor? It is needed as it provides an opportunity for doing necessary setup operations like initializing class variables, opening database connections or socket connections, etc. In simple terms, it is needed to setup the object before it can be used.

Example constructor
class Customer { private $first_name; private $last_name; private $outstanding_amount; public function __construct() { $first_name = ""; $last_name = ""; $outstanding_amount = 0; } public function setData($first_name, $last_name, $outstanding_amount) { $this->first_name = $first_name; $this->last_name = $last_name; $this->outstanding_amount = $outstanding_amount; } public function printData() { echo "Name : " . $first_name . " " . $this->last_name . "\n"; echo "Outstanding Amount : " . $this->outstanding_amount . "\n"; } } $c1 = new Customer(); $c1->setData("Sunil","Bhatia",0);

Parameterized Constructor or Argument Constructor


class Customer { private $first_name; private $last_name;

private $outstanding_amount;
public function __construct($first_name, $last_name, $outstanding_amount) { $this->setData($first_name, $last_name, $outstanding_amount); } public function setData($first_name, $last_name, $outstanding_amount) {

$this->first_name = $first_name;
$this->last_name = $last_name; $this->outstanding_amount = $outstanding_amount; } public function printData() {

echo "Name : " . $first_name . " " . $this->last_name . "\n";


echo "Outstanding Amount : " . $this->outstanding_amount . "\n"; } } $c1 = new Customer("Sunil","Bhatia",0);

Destructor

Definition of a Destructor A destructor is a special function of a class that is automatically executed whenever an object of a class is destroyed. What does this all mean? Lets revisit that definition in more simple terms. A destructor is a special function this means that a destructor is a function; but its special. But, why is it special? Its special because it is automatically executed or called when an object of a class is destroyed. An object of a class is destroyed when
1. 2. 3. it goes out of scope, when you specifically set it to null, when you unset it or when the program execution is over.

Why do we need a Destructor? It is needed as it provides an opportunity for doing necessary cleanup operations like unsetting internal class objects, closing database connections or socket connections, etc. In simple terms, it is needed to cleanup the object before it is destroyed. You should also read more about Garbage Collection to understand how clean up happens. Destructor: after the program completes its execution

Example destructor
class Customer {
private $first_name; private $last_name; private $outstanding_amount; public function __construct() { $first_name = ""; $last_name = ""; $outstanding_amount = 0; } public function setData($first_name, $last_name, $outstanding_amount) { $this->first_name = $first_name; $this->last_name = $last_name; $this->outstanding_amount = $outstanding_amount; } public function printData() { echo "Name : " . $first_name . " " . $last_name . "\n"; echo "Outstanding Amount : " . $outstanding_amount . "\n"; } }

Example destructor(cont)
class Order { private $order_id; private $customer; public function __construct($order_id, $customer) { $this->order_id = $order_id; $this->customer = $customer; } public function __destruct() { unset($this->order_id); unset($this->customer); } } $order_id = "L0001"; $c1 = new Customer(); $c1->setData("Sunil","Bhatia",0); $o = new Order($order_id, $c1);

Class Access Specifiers public, private and protected

Definition of Access Specifiers Access specifiers specify the level of access that the outside world (i.e. other class objects, external functions and global level code) have on the class methods and class data members. Access specifiers can either be public, private or protected. Why do we need Access specifiers Access specifiers are used as a key component of Encapsulation and Data Hiding. By using either of the access specifiers mentioned above i.e. public, private or protected you can hide or show the internals of your class to the outside world. Explanation of each access specifier 1. Private 2. Protected 3. Public

1. Private A private access specifier is used to hide the data member or member function to the outside world. This means that only the class that defines such data member and member functions have access them. Look at the example below:

Example private
class Customer { private $name; public function setName($name) { $this->name = $name; } public function getName() { return $this->name; } } $c = new Customer(); $c->setName("Sunil Bhatia"); echo $c->name; //error, $name cannot be accessed from outside the class //$name can only be accessed from within the class echo $c->getName(); //this works, as the methods of the class have access //to the private data members or methods

In the above example, echo $c->name will give you an error as $name in class Customer has been declared private and hence only be accessed by its member functions internally. Therefore, the following line echo $c->getName() will display the name.

2. Public A public access specifier provides the least protection to the internal data members and member functions. A public access specifier allows the outside world to access/modify the data members directly unlike the private access specifier. Look at the example below:

class Customer { public $name; public function setName($name) { $this->name = $name; }


public function getName() { return $this->name; } } $c = new Customer(); $c->setName("Sunil Bhatia"); echo $c->name; // this will work as it is public. $c->name = "New Name" ; // this does not give an error.

In the above example, echo $c->name will work as it has been declared as public and hence can be accessed by class member functions and the rest of the script.

3. Protected A protected access specifier is mainly used with inheritance. A data member or member function declared as protected will be accessed by its class and its base class but not from the outside world (i.e. rest of the script). We can also say that a protected data member is public for the class that declares it and its child class; but is private for the rest of the program (outside world). Look at the example below:

class Customer { protected $name; public function setName($name) { $this->name = $name; } public function getName() { return $this->name; } } class DiscountCustomer extends Customer { private $discount; public function setData($name, $discount) { $this->name = $name; //this is storing $name to the Customer //class $name variable. This works // as it is a protected variable $this->discount = $discount; } } $dc = new DiscountCustomer(); $dc->setData("Sunil Bhatia",10); echo $dc->name; // this does not work as $name is protected and hence // only available in Customer and DiscountCustomer class In the above example, echo $dc->name will not work work $name has been defined as a protected variable and hence it is only available in Customer and DiscountCustomer class.

Important Note of Access Specifier in PHP5 In PHP5, access specifiers are public by default. This means that if you dont specify an access specifier for a data member or method then the default public is applicable.

Key word Final in PHP

Khi nh ngha class hay method vi t kha FINAL: - i vi methode: khng th override t lp con cc phng thc c kha final lp CHA - i vi class: khi dng t kha final ta khng th extends t lp CHA

Example
Example #1 Final methods example <?php class BaseClass { public function test() { echo "BaseClass::test() called\n"; }

final public function moreTesting() { echo "BaseClass::moreTesting() called\n"; } } class ChildClass extends BaseClass { public function moreTesting() { echo "ChildClass::moreTesting() called\n"; } } // Results in Fatal error: Cannot override final method BaseClass::m oreTesting() ?>

Example
Example #2 Final class example <?php final class BaseClass { public function test() { echo "BaseClass::test() called\n"; }

// Here it doesn't matter if you specify the function as final or not final public function moreTesting() { echo "BaseClass::moreTesting() called\n"; } } class ChildClass extends BaseClass { } // Results in Fatal error: Class ChildClass may not inherit from final c lass (BaseClass) ?> Note: Properties cannot be declared final, only classes and methods may be declared as final.

Abstract
What is an Abstract Class? An abstract class is a class with or without data members that provides some functionality and leaves the remaining functionality for its child class to implement. The child class must provide the functionality not provided by the abstract class or else the child class also becomes abstract. Objects of an abstract and interface class cannot be created i.e. only objects of concrete class can be created To define a class as Abstract, the keyword abstract is to be used e.g. abstract class ClassName { }

Example of Abstract Class


abstract class Furniture { private $height, width, length; public function setData($h, $w, $l) { $this->height = $h; $this->width = $w; $this->length = $l; } //this function is declared as abstract and hence the function //body will have to be provided in the child class public abstract function getPrice(); } class BookShelf extends Furniture { private $price; public setData($h, $w, $l, $p) { parent::setData($h, $w, $l); $this->price = $p; } //this is the function body of the parent abstract method public function getPrice() { return $this->price; } }

Private methods cannot be abstract If a method is defined as abstract then it cannot be declared as private (it can only be public or protected). This is because a private method cannot be inherited. abstract class BaseClass { private abstract function myFun(); } class DerivedClass extends BaseClass { public function myFun() { //logic here } } $d = new DerivedClass(); //will cause error

Interface
What is an Interface? An interface is a contract between unrelated objects to perform a common function. An interface enables you to specify that an object is capable of performing a certain function, but it does not necessarily tell you how the object does so, this means that it leaves for classes implementing an interface to define its behaviour. To extend from an Interface, keyword implements is used. We can have a class extend from more than one Interface.

Interfaces

Object Interfaces Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled. Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined. All methods declared in an interface must be public, this is the nature of an interface. implements To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.

Example #1 Interface example <?php // Declare the interface 'iTemplate' interface iTemplate { public function setVariable($name, $var); public function getHtml($template); } // Implement the interface // This will work class Template implements iTemplate { private $vars = array(); public function setVariable($name, $var) { $this->vars[$name] = $var; } public function getHtml($template) { foreach($this->vars as $name => $value) { $template = str_replace('{' . $name . '}', $value, $template); } return $template; } } // This will not work // Fatal error: Class BadTemplate contains 1 abstract methods // and must therefore be declared abstract (iTemplate::getHtml) class BadTemplate implements iTemplate { private $vars = array(); public function setVariable($name, $var) { $this->vars[$name] = $var; } } ?>

Example #2 Extendable Interfaces <?php interface a { public function foo(); } interface b extends a { public function baz(Baz $baz); } // This will work class c implements b { public function foo() { } public function baz(Baz $baz) { } } // This will not work and result in a fatal error class d implements b { public function foo() { } public function baz(Foo $foo) { } } ?>

Example #3 Multiple interface inheritance <?php interface a { public function foo(); }

interface b { public function bar(); } interface c extends a, b { public function baz(); } class d implements c { public function foo() { } public function bar() { } public function baz() { } } ?>

Difference between Abstract Class and Interface Abstract Classes An abstract class can provide some functionality and leave the rest for derived class The derived class may or may not override the concrete functions defined in base class The child class extended from an abstract class should logically be related Interface An interface cannot contain any functionality. It only contains definitions of the methods The derived class must provide code for all the methods defined in the interface Completely different and non-related classes can be logically be grouped together using an interface

Inheritance
class Person { private $name; private $address;

To inherit in PHP5, you should use the keyword extends in the class definition. In PHP5 only single inheritance is allowed. Look at the example below:

public function getName() { return $this->name; } }

class Customer extends Person {


private $customer_id; private $record_date; public getCustomerId() { return $this->customer_id; } public getCustomerName() { return $this->getName();// getName() is in Person }

Mt s ch nh trong OOP

V d ta c 1 class nh sau

Class Student{ Var $name; Var $birth;

Public function Student(){


$this->name=Nguyen Van C; $this->birth= 02/10/1980; }

Public function show(){ echo $this->name;


echo $this->birth; } }

To 1 i tng ca lp ta vit: $student = new Student(); truy xut thuc tnh v phng thc cu lp ta vit: $student->name; $student->show(); Note: khng vit $student->$name

K tha extends

V d ta c 1 lp Class Person{ Var $name; Var $birth; Public function Person(){ $this->name=Nguyen Thi Teo;

$this->birth=01/02/1989;
} Public function display(){ Echo $this->name. .$this->birth; } } Class Student extends Person(){ Var $ID; //ma so sinh vien Public __construct(){ $this->ID=12345; } Public function display(){ Parent::display();//gi phng thc ca lp cha Person::display() } } $student = new Student(); $student->name;

$student->display();//gi phng thc ca lp con

static

Mt thuc tnh c khai bo vi t kha static, th cc i tng thuc lp s khng th truy xut c thuc tnh . Cng v vy $this cng khng th s dn <?php class Operators { public static $a = 5; public static $b = 6; private $s;

public function sum()


{ return $this->s = $this->a + $this->b; } } $ob = new Operators; echo $ob->a; //Khng ly c gi tr a echo Operators ::$b; //Ly c gi tr b ?>

Constants

Constants
Chng ta c th nh ngha mt hng trn mt lp. Hng khc vi bin ch n l gi tr khng thay i v khai bo khng c $ trc. Nu nh ngha mt hng th tn hng phi khng c trng tn vi bin, lp, hm v kt qu ca mt php ton hay kt qu ca mt hm. nh ngha mt hng c php nh sau:

const myConst = 'value of myConst'; Vic ly gi tr ca hng cng gn ging nh bin tuy nhin ta ch ly c qua ton t :: hoc thng qua mt phng thc. V d:
<?php class MyClass { const myConst = 'My Constant'; function showConst() { echo MyClass::myConst; } } $ob = new MyClass; $ob->showConst(); echo MyClass::myConst; ?>

Abstraction

PHP 5 gii thiu n chng ta cc lp v phng thc tru tng (abstract). Cc lp c nh ngha abstract th n s khng cho php to cc instance, ngha l ta s khng th to c cc i tng thuc lp . Cc phng thc c nh ngha abstract ch n gin l vit m t phng thc , khng nh ngha chng, ngha l ta ch khai bo tn hm theo ng cu trc m bn trong thn hm khng nh ngha g ht. Vd:

Object Interfaces

Object Interfaces cho php bn ch nh phng thc no ca lp phi c thc thi, m khng phi nh ngha phng thc lm vic nh th no. Cc bn xem v d sau:

Overloading

Overloading Tt c cc phng s dng gi hoc truy xut chng ta u c th overload qua cc phng thc _call, _set, _get. Trong PHP 5 chng ta c th overload thm 2 phng thc _isset() v _unset() bng 2 phng thc _isset v _unset. Tt c cc phng thc chng ta mun overload th phi c m t chng public v khng c nh ngha static. Cc phng thc c overload c m t nh sau: void __set ( string $name, mixed $value ): c thc hin khi chng ta dng lnh gn gi tr cho bin. mixed __get ( string $name ): Thc hin khi chng ta dng lnh unset hoc gn mt gi tr mi cho bin. bool __isset ( string $name ): Thc hin khi chng ta dng n phng thc isset() void __unset ( string $name ): Thc hin khi chng ta dng phng thc unset();

Thank you reading (^_^)

Das könnte Ihnen auch gefallen