PHP Oop
PHP Oop
Objects:
Defining classes:
Classes are defined using the keyword ‘class’
Ex: class Person {
……..
}
Defining methods:
Methods are defined using the keyword ‘function’
Ex: class Person {
function sayHello() {
…………………
}
}
OOP with PHP
Instantiating a class:
Instantiating a class means creating an object of type of a given
class
Each object of a class has it’s own identity
Ex: <?php
class Person {
………………
}
$person = new Person();
?>
OOP with PHP
Referencing an instance:
Reference assignment is automatic for objects in PHP 5
Same is not true in case of PHP 4 [Must use ‘&’ explicitly]
Ex: // In PHP 5
$img = new Image();
$img2 = $img; // Now, imag2 references imag
// In PHP 4
$img = new Image();
$img2 =& $img;
OOP with PHP
Constructor example:
class Bar {
public function Bar() {
// treated as constructor in PHP 5.3.0-5.3.2
// treated as regular method as of PHP 5.3.3
}
}
class Bar {
function __construct() {
// Constructors in PHP 5.3.3 and above
}
}
OOP with PHP
Destructors
Destructors are usually used to deallocate memory and do other
cleanup operations
A destructor is called for a class object when that object passes out
of scope or is explicitly deleted
Ex:
class Bar {
function __destruct() {
…...........
}
}
OOP with PHP
Class inheritance:
The new class created is called a Derived class and the old
class used as a base is called a Base class
The derived class will inherit all the features of the base class
OOP with PHP
Inheritance in PHP
Example:
<php
class Foo {
function sayThis() {
echo “This is in Foo class”;
}
}
class Bar extends Foo {
}
$foo = new Foo();
$bar = new Bar();
$foo->sayThis();
$bar->sayThis();
?>
THANK YOU
Resources,
http://www.php.net/manual/en/oop5.intro.php
http://www.lynda.com/