Category Archives: OOPS Concepts

Paamayim Nekudotayim Operator

In PHP, the scope resolution operator is also called Paamayim Nekudotayim (Hebrew Language), which means “twice colon” or “double dot twice”.

 

As you might know PHP 3.0 was created by the Zend team, and it was powered by the Zend Engine 0.5.The name “Paamayim Nekudotayim” was introduced in the Israeli-developed Zend Engine 0.5 used in PHP 3. Although it has been confusing to many developers who don’t speak Hebrew Language, it is still being used in PHP 5.

 

Paamayim Nekudotayim or Scope Resolution Operator (::)

 

It is a token that allows access to static, constant, and overridden properties or methods of a class.

When referencing these items from outside the class definition, use the name of the class.

As of PHP 5.3.0, it’s possible to reference the class using a variable. The variable’s value can not be a keyword (e.g. self, parent and static).

[php]
<?php

class OtherClass extends MyClass
{
public static $my_static = ‘static variable’;
public static function doubleColon() {
echo parent::CONST_VALUE;
echo self::$my_static;
}
}

$classname = ‘OtherClass’;
echo $classname::doubleColon(); // As of PHP 5.3.0
OtherClass::doubleColon();

?>
[/php]

 

Three special keywords self, parent and static are used to access properties or methods from inside the class definition.

 

PHP Objects

PHP: Object Oriented Programming (OOP) php objects

 

A class is a ‘blueprint’ for an object, just like a function that you’d declare and use, a class merely describes a type of object. Before you can do useful logical work with it, you need to create an object (in pure OOP terms instance of a class) using a process called instantiation.
Once you have an object, you can call the methods that are defined in the class.

 

Class can also be defined as a ‘Black Box’ from where you can create objects and access its attributes or properties (variables) and methods (functions).

 

OOP is very useful if you have a large number of objects of the same type in a system in that case you just have to create the objects and then manipulate them all in the same way, without rewriting any code. Moreover, an object is able to maintain it’s state (variable values and such related) throughout the execution of the program.

 

Here is small example of class and object.

[php]
<?php
class Scriptarticle {

public $post_date, $author;

public function Post() {
echo "You are in post method";
}

public function Page() {
echo "You are in page method";
}

public function Comment() {
// we can write the logic related to comment here.
echo "You are in comment method";
}
}

// class intstantiated
$objectOfScriptarticle = new Scriptarticle();

// varible initilisation
$objectOfScriptarticle->author =’Mahesh’;

// use of class method
$objectOfScriptarticle->Post();
?>
[/php]

You can also know weather the variable you are using is an object of a class or not by the below function.

[php]
bool is_object ( mixed $var )
[/php]

PHP: Key difference between abstract class and interface

Difference between Abstract class and Interface PHP

 

An abstract class is a class 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 (parent) or else the child class also becomes abstract.

 

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

 

[php]

abstract class ClassName { }

[/php]

 

Abstract class must have at least one abstract method (only declared not defined).
If you want to use this class then you have to inherit it.

 

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 behavior (logics).

 

Abstract class and interface cannot be instantiated i.e. only concrete class can be instantiated
To extend from an Interface, a keyword implement is used.

 

Difference between Abstract Class and Interface:

 

An abstract class can provide some functionality and leave the rest for derived class to provide.
An interface cannot contain any functionality. It only contains definitions of the methods.

 

The derived class may or may not override the concrete functions defined in base abstract class (Not mandatory).
The derived class must provide code or login (method definition) for all the methods defined in the interface (Mandatory).

 

The child class extended from an abstract class should logically be related.
Completely different and non-related classes can be logically be grouped together using an interface.

 

For abstract class a method must be declared as abstract. Abstract methods doesn’t have any implementation/definition.
In interface all the methods by default are abstract methods only so you need not use abstract keyword at all.

 

The Abstract methods can declare with Access modifiers like public, protected(not private).When implementing in subclass these methods must be defined with the same (or a less restricted) visibility.
All methods declared in an interface must be public.

 

Abstract class can contain variables and concrete methods.
Interfaces cannot contain variables and concrete methods except constants.

 

A class can inherit only one Abstract class and multiple inheritance is not possible for Abstract class.
A class can implement many interfaces and multiple interface inheritance is possible.

 

You can use interface as marker (An interface having no methods is called as a Marker Interface)
You can also do in abstract class to making all the methods abstract but it is better always use interface as marker.

 

In general, prefer interfaces if you don’t need to use an abstract class, because they provide more design flexibility.

Note:

  • Private methods cannot be abstract because private method cannot be inherited. If a method is defined as abstract then it can only be public or protected.

 

Difference between PHP4 and PHP5

A Quick view on difference between PHP4 and PHP5

PHP5 has improvements in design, security, and stability as compared to PHP4, there are so many features of OOP added in PHP5 to make it more powerful and useful. If you want more details just go to http://www.php.net and find changes in php.

 

Object Model/Passed by Reference
This is an important update. In PHP4, everything was passed by value including objects. This has changed in PHP5 all objects are now passed by reference.

 

[php]

$john = new Employee();
$john->age = ’22’;

$pamella = $john;
$pamella->age = ’20’;

echo $john->age; // Will be ’20’

[/php]

 

The above code fragment was very common in PHP4.If you needed to duplicate an object; you simply copied it by assigning it to another variable. But in PHP5 you must use the new ‘clone’ keyword.

 

New Functions/Methods
In PHP5, there are added some of new functions. You can get listing of all of these by PHP Manual.

 

New Extensions
There are some new default extensions included in PHP5.

PDO for working with databases. It is an Object Oriented interface (layer) for interacting with any type of database.
SimpleXML for easy processing of XML data.

DOM and XSL extensions are available for a improving XML related stuff.
Hash extension gives you a lot of ways (functions) to encrypt data or secure information if you need more then the md5.

 

Class Const (Constant)
In PHP5, you can create class constants with a keyword const that act same as define()’ed constants, but these should be contained within a class definition and can be accessed with the :: (scope resolution) operator.

 

Static Methods/Properties
Static methods and properties are also available in PHP5.If you declare a class member as static, then it makes that member/method accessible (through the :: operator) without an instance(object).

 

Visibility/ Access Control Modifiers

Class methods and properties now have visibility.PHP has 3 levels of visibility

Public makes methods accessible to everyone and properties readable and writable by everyone.

Protected makes members accessible to the class itself and any subclasses of that.

Private makes members only available to the class itself.

 

Magic Methods
There are a number of “magic methods” that add an assortment to functionality to your classes. Naming of “magic methods” prefixed with a double-underscore.
Some magic methods are __call, __get, __set and __toString.

 

The __autoload Function
Using a specially named function __autoload() you can automatically load object files(class) when PHP encounters a class that hasn’t been defined yet. Instead of large chunks of include’s at the top of your scripts, you can define a simple autoload function to include them automatically.

[php]

function __autoload($class_name) {
require_once "./includes/classes/$class_name.inc.php";
}

[/php]

 

Constructors and Destructors
In PHP4, a constructor was simply a method that had the same name as the class itself.This caused some problem since if you changed the name of the class, you would have to go through and change every occurrence of that name

But in PHP5, all constructors are named __construct().That is, the word construct prefixed by two underscores.Other then this name change, a constructor works the same way.

Also, __destruct() allows you to write code that will be executed when the object is destroyed.

 

Abstract Classes
An abstract class cannot itself be instantiated, it is purely used to define a model where other classes extend.You must declare a class abstract if it contains any abstract methods.Any methods marked as abstract must be defined within any classes that extend the class.Note that you can also include full method definitions within an abstract class along with any abstract methods.

PHP5 make you able to declare a class as abstract.

 

Interfaces
PHP5 introduces interfaces to help in common APIs design.
An interface defines the methods a class must implement. All the methods defined in an interface must be public.

The one big advantage to using interfaces is that a class can implement any number of interfaces. You can extend only a parent class, but can implement an unlimited number of interfaces.

 

Also, have a look on difference between Abstract class and interface.

 

Finality
You can now use the final keyword to indicate that a method cannot be overridden by a child. You can also declare an entire class as final which prevents it from having any children at all.

 

Type Hinting
PHP5 introduces some limited type hinting. This means you can enforce what kinds of variables are passed to functions or class methods. But right now this only work for classes or arrays so no other scalar types like integers or strings.

 

To add a type hint to a parameter, you specify the name of the class before the $.Be sure that if you specify a class name, the type will be satisfied with all of its subclasses as well.

[php]

function echo_user(User $user) {
echo $user->getUsername();
}

[/php]

 

If the passed parameter is not User (or a subclass of User), then PHP will throw a fatal error.

 

Exceptions
PHP5 have included exceptions. By using an exception however, you will gain more control, the simple trigger_error notices we were stuck with before.

 

An exception is just an object. When an error occurs, you throw an exception. When an exception is thrown, the rest of the PHP code following will not be executed. When you are about to perform something “risky or buggy”, surround your code with a try block. If an exception is thrown, then your following catch block is there to catch the error and handle it accordingly. If there is no catch block, a fatal error occurs.

[php]

try {
$cache->write();
} catch (AccessDeniedException $e) {
die(‘Could not write the cache, access denied.’);
} catch (Exception $e) {
die(‘An unknown error occurred: ‘ .$e->getMessage());
}

[/php]

 

E_STRICT Error Level
There is a new error level defined as E_STRICT.It is not included in E_ALL, if you wish to use this new level you must specify it explicitly.E_STRICT will notify you when you use depreciated code.

 

Foreach Construct and By-Reference Value
The foreach construct now lets you define the ‘value’ as a reference instead of a copy.

[php]

foreach($array as $k => &$v) {
$v = htmlentities($v);
}

[/php]

 

Compatibility Issues
The PHP manual has a list of changes that will affect backwards compatibility. Here are some of those.

 

array_merge() will now give you warnings if any of the parameters are not arrays. In PHP4, you could get away with merging non-arrays with arrays (and the items would just be added if they were say, a string).

 

As discussed above, objects are now passed by references. If you want to copy a object, make sure to use the clone keyword.

get_*() now return names as they were defined. If a class was called MyClass, then get_class() will return that.

 

For a detailed view of the Backwards Compatibility Issues, you can also check the PHP Manual, which contains a lot of useful information on this.

Difference between $this and self in PHP

What is the difference between this and self in PHP OOP?

 

PHP classes can have static functions and static variables.Declaring class methods or properties as static make them accessible without needing an instance of the class or an object.

 

Static functions and variables in classes are not associated with any object, but associated with the class definition itself.
You can say all instances of a class share the same static variable and functions.

 

Inside a class definition, $this refers to the current object, while self(not $self) refers to the current class.
self does not use a preceding $ because self does n’t represent a variable but the class construct itself.$this does reference a specific variable so it has a $ prefix.

 

It is necessary to refer to a class element using self & refer to an object element using $this, use $this->var for non-static variables, use self::$var for static variables and same for methods.

 

[php]

class demoClass
{
public $var;
public static $svar;

public function regular_function()
{ echo $this->var; }

public static function static_function()
{ echo self::$svar; }

public static function another_static_fn()
{ self::static_function(); }

public function regular_fn_using_static_var()
{ echo self::$svar; }
}

demoClass::$svar = "Script";

$obj = new demoClass();
$obj->var = "Article";

echo demoClass::static_function();
echo $obj->regular_function();

[/php]

 

Note:

  • static functions can only use static variables. The way static functions and static variables are referenced is self::functionName() or self::variableName.
  • Regular functions and variables of a class need an object to be referenced.

 

OOPS: Classes in php

OOPS Concept: Introducing Classes in php

 

You all know that Classes are the most important part of OOP.

 

A class is simply a template or blueprint that contains the various attributes and functions of an object of the class.
Class is mainly composed of three things :  name, attributes, and operations.We can also say that class is a composite data type same as we have used struct in C and C++.

 

Class would be the type, and an object would be the variable. eg.

 

Consider a class Car.
A car class will have the following attributes:

1. Color
2. Engine
3. Tyres
4. Headlights
5. Seats
6. Steering

It will also have the following function/operations
1. Power Brake
2. Blow Horn
3. Pickup and Drive etc

 

A class gives you only the attributes and function.

Lets think in general there are so many company manufacture the car,they can increase the function and attributes. After putting all these in a real world then a car make up,then it’s called object(real entity),the base or template or blueprint is car,so car is a class.

 

In real world, you’ll often find many individual objects all of the same kind. As an example, there may be thousands of other bikes, all of the same make and model. Each bike has built from the same blueprint. In object-oriented terms, we say that the bike is an instance of the class of objects known as bikes.