Tag Archives: OOPS

How to get more records or data on scroll down of page in PHP like facebook?

Do you know How to display more records while scrolling the page down using JQuery and PHP?

If you are familiar with jQuery and PHP, then it is not hard nut to crack.

Have a look on below code and you can do the same. Include JQuery library File:

Include JQuery library File:
<script type=’text/javascript’ src=’http://code.jquery.com/jquery-1.7.2.js’></script>


Create or call using a simple jQuery function in JS file (If you want to make the codeĀ separate).

[code lang=”js”]


function scrollFunc()
if($(window).scrollTop() == ($(document).height() – $(window).height())){

var offset = $(‘[id^=&quot;dataRow_&quot;]’).length;
var records = $(&quot;.totNum&quot;).text();


if(records != offset){

$(&quot;#loaderImg&quot;).html(‘&lt;img src=&quot;images/ajax-loader.gif&quot; /&gt;’);




function loadMoreRecords(offset){

// here we call ajax to add more records in our page.

type: ‘get’,
url: ‘loadMyPageRecords.php’,
data: ‘offset=’+offset,

success: function(data){

$(&quot;.loadData :last&quot;).after(data);


error: function(data){
alert(&quot;ajax response error…&quot;+data);






How simple !! Isn’t it?

If you still face any issue, post your comments.



How to achieve and use Polymorphism in PHP

Polymorphism – the concept


Polymorphism is a Greek word that means “many forms”. In object-oriented programming, polymorphism is a mechanism by which objects of different types can process data through a single interface. Using a typical illustrative example, a program might define a type of object called Animal, containing a function called talk() and, through inheritance, derive object sub-types such as Cat, Dog, etc. that each have their own specific implementation of the talk() function. The mechanism of polymorphism allows such a program to call the talk() function without actually knowing whether it is calling it for a Cat, Dog, or any other derivative Animal, while executing the correct function for the specific type of Animal.


Why method polymorphism cannot be achieved in PHP?
In languages like Java where in a function sum (int, int) differs from sum (float, float), the method sum() has many forms depending on the parameters being passed to it.

But in PHP it is not possible because you can have a method that accepts two parameters and call it by passing three parameters (allows variable arguments). 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.


Polymorphism is not the same as method overloading or method overriding (in OOP, a method is a function that belongs to a class, while the class variables are referred to as its members) and should not be confused with these.


Method overloading is where a class has two or more functions of the same name, but accepting a different number and/or data types of parameters.


Method overriding is where a child class (one derived through inheritance) defines a function with the same name and parameters as a function in its parent class, but provides a different implementation of the function. This is not the same as polymorphism, as it does not necessarily involve late-binding, however overriding is part of the mechanism by which polymorphism is accomplished.



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.



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 = new DerivedClass();





DerivedClass method called


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 BaseClass. Within the processClass() the method myMethod() is being called. Since the method is being called on the class variable of BaseClass, it would not be wrong to assume that myMethod() of class BaseClass will be called. But, 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.


I hope the above makes sense and hasn’t been too confusing as you know this is difficult to explain in clear English šŸ™


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.

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

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

bool is_object ( mixed $var )

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



abstract class ClassName { }



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.


  • 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.



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

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

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



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.


function __autoload($class_name) {
require_once "./includes/classes/$class_name.inc.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.


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.


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.


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



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


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.


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



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.


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



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.



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();




  • 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.