Wednesday, February 18, 2009

Polymorphism

Polymorphism is derived from two Greek words. Poly (meaning many) and morph (meaning forms). Polymorphism means many forms. In C you have two methods with the same name that have different function signatures and hence by passing the correct function signature you can invoke the correct method.
The meaning with Object Oriented languages changes. With Object Oriented language polymorphism happens:
When the decision to invoke a function call is made by inspecting the object at runtime it is called Polymorphism
Method polymorphism cannot be achieved in PHP :
The reason why polymorphism for methods is not possible in PHP is because you can have a method that accepts two parameters and call it by passing three parameters. This is because PHP is not strict and contains methods like func_num_args() and func_get_arg() to find the number of arguments passed and get a particular parameter.
Because PHP is not type strict and allows variable arguments, this is why method polymorphism is not possible.
PHP 5 Polymorphism
Since PHP 5 introduces the concept of Type Hinting, polymorphism is possible with class methods. The basis of polymorphism is Inheritance and overridden methods.
Eg:

class BaseClass {
public function myMethod() {
echo "BaseClass method called";
}
}

class DerivedClass extends BaseClass {
public function myMethod() {
echo "DerivedClass method called";
}
}

function processClass(BaseClass $c) {
$c->myMethod();
}

$c = new DerivedClass();
processClass($c);

In the above example, object $c of class DerievedClass is executed and passed to the processClass() method. The parameter accepted in processClass() is that of BassClass. Within the processClass() the method myMethod() is being called. As per the definition “When the decision to invoke a function call is made by inspecting the object at runtime it is called Polymorphism”, myMethod() will be called on object DerievedClass. The reason why this happens is because the object of DerievedClass is being passed and hence the method myMethod() of DerievedClass will be called.

Final Class and Methods
Final Class :

A final class is a class that cannot be extended. To declare a class as final, you need to prefix the ‘class’ keyword with ‘final’.
Eg:
final class BaseClass {
public function myMethod() {
echo "BaseClass method called";
}
}

//this will cause Compile error
class DerivedClass extends BaseClass {
public function myMethod() {
echo "DerivedClass method called";
}
}

$c = new DerivedClass();
$c->myMethod();

In the above example, BaseClass is declared as final and hence cannot be extended (inherited). DerivedClass tries to extend from BaseClass and hence the compiler will throw a compile error.
Final Method :
A final method is a method that cannot be overridden. To declare a method as final, you need to prefix the function name with the ‘final’ keyword.
Eg:
class BaseClass {
final public function myMethod() {
echo "BaseClass method called";
}
}

class DerivedClass extends BaseClass {
//this will cause Compile error
public function myMethod() {
echo "DerivedClass method called";
}
}

$c = new DerivedClass();
$c->myMethod();
In the above example, DerivedClass extends from BaseClass. BaseClass has the method myMethod() declared as final and this cannot be overridden. In this case the compiler causes a compile error.

Static Data Member :
A data member that is commonly available to all objects of a class is called a static member. static members share the memory space between all objects of the same class.

Defining static data members in PHP5
To define a static member in PHP5 you need to prefix the class member name with the keyword ’static’.
Eg:
class Customer {

private $first_name; // regular member
static public $instance_count; //static data member

}
Accessing static data members in PHP5
A static member data can be accessed using the name of the class along with the scope resolution operator (::) i.e. you don’t need to create an instance of that class
Eg:
class Customer {

static public $instance_count = 0; //static data member

public function __construct() {
Customer::$instance_count++;
}

public function __destruct() {
Customer::$instance_count--;
}

public function getFirstName() {
//body of method
}

static public function getInstanceCount() {
//body of method
}
}

$c1 = new Customer();
$c2 = new Customer();

echo Customer::$instance_count;

Output:
2
In the above example, $instance_count is a static data member. Every time a new object is created the constructor is executed and the $instance_count variable is incremented by one. To echo the value contained in $instance_count variable, we use the :: (scope resolution) operator.

Static Method :
A static method is a class method that can be called without creating an instance of a class. Such methods are useful when creating utility classes.
Defining static methods in PHP5
To define a static data methods in PHP5 you need to prefix the class method name with the keyword ’static’.
Eg:
class Customer {

public function getFirstName() {
//body of method
}

static public function getInstanceCount() {
//body of method
}
}
Accessing static method in PHP5
A static method can be accessed using the name of the class along with the scope resolution operator (::) i.e. you don’t need to create an instance of that class. However, you can also access it with an instance variable.
Eg:

class Customer {

static public $instance_count = 0; //static data member

public function __construct() {
Customer::$instance_count++;
}

public function __destruct() {
Customer::$instance_count--;
}

public function getFirstName() {
//body of method
}

static public function getInstanceCount() {
return Customer::$instance_count;
}
}

$c1 = new Customer();
$c2 = new Customer();

echo Customer::getInstanceCount(); //this is using the scope resolution operator
echo $c1->getInstanceCount(); //this is using the instance variable
Output:
2
2
Rules to keep in mind for static methods

  • A static method can only access static data members

  • A static method does not have access to the $this variable

Thursday, February 12, 2009

Access specifiers:
Access specifiers are used to identify access rights for the data and member functions of the class. 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. There are three main types of access specifiers in PHP.

  • private

  • public

  • protected


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.
Eg:

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.

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.
Eg:
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 it’s child class; but is private for the rest of the program (outside world).
Eg:
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 don’t specify an access specifier for a data member or method then the default ‘public’ is applicable.

Tuesday, February 10, 2009

Bit about OOP

OOP is the common abbreviation for Object-Oriented Programming. Object-Oriented Programming (OOP) is different from procedural programming languages (C, Pascal, etc.). OOPS is a type of programming in which programmers define not only the data type of a data structure, but also the types of operations (functions) that can be applied to the data structure . In this way, the data structure becomes an object that includes both data and functions. In addition, programmers can create relationships between one object and another. For example, objects can inherit characteristics from other objects.
One of the principal advantages of object-oriented programming techniques over procedural programming techniques is that they enable programmers to create modules that do not need to be changed when a new type of object is added. A programmer can simply create a new object that inherits many of its features from existing objects. This makes object-oriented programs easier to modify.

What is an Object

Object is a instance of a class. An object is a bunch of variables and functions all encapsulated into a single entity. The object can then be called rather than calling the variables or functions themselves. Within an object there are methods and properties. The methods are functions that manipulate data within the object. The properties are variables that hold information about the object.

What is a Class
A class is the blueprint for your object. The class contains the methods and properties, or the characteristics of the object. It defines the object.
The class holds the definition, and the object holds the value.
The syntax is used for writing the class is as follows. We declare class in PHP by using the class keyword.

class vehicle
{
/*** define public properties ***/

public $color;
public $price;
public function showPrice(){
echo 'This vehicle costs '.$this->price.'.
';
}

} /** end of class **/
?>
This is the class definition for class vehicle. we can now create one, or many, vehicle objects from that class definition. To create a new object from the class definition we use the new keyword.
/*** create a new vehicle object ***/
$vehicle = new vehicle;
$vehicle->price =100000;

/*** call the showPrice method ***/
$vehicle->showPrice();
?>
What is the difference between an object and a class?
1) class:class is an abstract data type in which both Member
functions and member variable are declared that means
a class is user defined data type in which we will be able to
declare both methods and variable.
object : Object is an Instance of the class. The class is a
valid one when object is created.

2) Class is a static entity, while object is a dynamic entity.
class is the template for members and methods
Object is the physical reality to access the members and
Methods.
For one class we will have more number of Objects.
3) Class is just a template. It does not allocate memory
space. When instantiate the object, allocates the memory
space.

Constructors

Constructors are functions in a class that are automatically called when you create a new instance of a class with new.
Constructors are used for initialization of an object.
In PHP4 we called to constructor with the same name as a class. So, if you have a class named MyClass, constructor is a function named MyClass.
In PHP5 we call to constructor with the function name __construct.
If you inherit the class, The constructor of the inherited class is executed implicitly. The constructor of the parent class will not be executed implicitly. If you want to execute parent constructor you have to call it explicitly in a subclass constructor with:
parent::ClassName
or
parent::__construct

Destructor
Destructor is a function which is called right after you release an object. Releasing object means that you do not need it or use it anymore. This makes destructor suitable for any final actions you want to perform.
Destructor is a PHP5 feature. PHP4 does not have destructors at all.
Destructor is a function called __destruct(). As a constructor, this function can not be called directly. It will be called implicitly when you release your object.

eg:

Class Animal
{
public $type;
public $sound;

/* Constructor in PHP5 */
public function _construct($type,$sound)
{
$this->type = $type;
$this->sound = $sound;
}

/* Constructor in PHP4 */
public function Animal($type,$sound)
{
$this->type = $type;
$this->sound = $sound;
}

}

class Cat extends Animal
{
public $name;


// this is consructor
public function __construct($name,$type,$sound)
{
$this->name = $name;
parent::__construct($type,$sound);
}

// this is destructor
function __destruct()
{
echo "Cat Object Released\n";
}

}


$cat = new Cat("Sweety", ”Cat”,” meeoow!”);


$this
$this is a pseudo-variable. Within a class definition, you do not know under which name the object will be accessible in your program. So we used $this to access the variable and function of an object in the class definition. $this is referred to the ‘current object’.

Inheritance
Definition of Inheritance:
Inheritance is the mechanism of deriving a new class from an existing class. It allows a sub-class / child class to share/inherit the attributes and behaviors of a base-class or parent class.
PHP5 Inheritance :
To inherit in PHP5, you should use the keyword ‘extends’ in the class definition. In PHP5 only single inheritance is allowed. The base class called the parent class and extended class called the child class or derived class. Child class has all the properties and method of the parent class which are public or protected.
Eg :-
class Person {
private $name;
private $address;

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
}
}

In the above example, class Customer extends from the Person class. This means that Customer class is the child class and the Person base class. The child class Customer extends the method getName() and calls it in the getCustomerName() method of the Customer class.