Friday, 6 November 2015

PHP-Object-Oriented-Concepts

02:13

PHP   Object     Oriented       Concepts    :

Before we go in detail, lets define important terms related to Object Oriented Programming :

·        Class: This is a programmer-defined data type, which includes local functions as well as local data. You can think of a class as a template for making many instances of the same kind (or class) of object.
·        Object: An individual instance of the data structure defined by a class. You define a class once and then make many objects that belong to it. Objects are also known as instance.
·        Member Variable: These are the variables defined inside a class. This data will be invisible to the outside of the class and can be accessed via member functions. These variables are called attribute of the object once an object is created.
·        Member function: These are the function defined inside a class and are used to access object data.
·        Inheritance: When a class is defined by inheriting existing function of a parent class then it is called inheritance. Here child class will inherit all or few member functions and variables of a parent class.
·        Parent class: A class that is inherited from by another class. This is also called a base class or super class.
·        Child Class: A class that inherits from another class. This is also called a subclass or derived class.
·        Polymorphism: This is an object oriented concept where same function can be used for different purposes. For example function name will remain same but it make take different number of arguments and can do different task.
·        Overloading: a type of polymorphism in which some or all of operators have different implementations depending on the types of their arguments. Similarly functions can also be overloaded with different implementation.
·        Data Abstraction: Any representation of data in which the implementation details are hidden (abstracted).
·        Encapsulation: refers to a concept where we encapsulate all the data and member functions together to form an object.
·        Constructor: refers to a special type of function which will be called automatically whenever there is an object formation from a class.
·        Destructors: refers to a special type of function which will be called automatically whenever an object is deleted or goes out of scope.

Example   :

Here is an example which defines a   class of   Books     type  :
<?php
class  Books{
    /* Member variables */
    var $price;
    var $title;
    /* Member functions */
    function setPrice($par)
{
       $this->price = $par;
    }
    function getPrice(){
       echo $this->price ."<br/>";
    }
    function setTitle($par){
       $this->title = $par;
    }
    function getTitle(){
       echo $this->title ." <br/>";
    }
}
?>
The variable $this is a special variable and it refers to the same object ie.  itself.

Creating   Objects   in  PHP  :

 

Once you defined your class, then you can create as many objects as you like of that class type. Following is an example of how to create object using new operator.

$physics = new Books;
$maths = new Books;
$chemistry = new Books;

Here we have created three objects and these objects are independent of each other and they will have their existance separately. Next we will see how to access member function and process member variables.

Calling Member Functions

After creating your objects, you will be able to call member functions related to that object. One member function will be able to process member variable of related object only.
Following example shows how to set title and prices for the three books  by  calling  member  functions.
$physics->setTitle( "Physics for High School" );
$chemistry->setTitle( "Advanced Chemistry" );
$maths->setTitle( "Algebra" );
 
$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );

 

Constructor   Functions   :

 

Constructor Functions are special type of functions which are called automatically whenever an object is created. So we take full advantage of this behaviour, by initializing many things through constructor functions.
PHP provides a special function   called __construct()   to define a constructor. You can pass as many as arguments you like into the constructor function.
Following example will create one constructor for Books class and it will initialize price and title for the book at the time of object creation.

function __construct( $par1, $par2 ){
   $this->price = $par1;
   $this->title = $par2;
}

 

 

Destructor   :

 

Like a constructor function you can define a destructor function using function __destruct().  You can release all the resourceses with-in a destructor.
Example for constructor & Destructor  :

<?php
class   example
{

function   __construct()
{

echo "constructor is called & object  is created";
echo "<br>";

}

Function  __destruct()
{

echo "destructor is called & object is free";

}
}
$obj=new  example();

?>

Inheritance   :

 

PHP class definitions can optionally inherit from a parent class definition by using the extends clause. The syntax is as follows:
class Child extends Parent {
     <definition body>
  }
The effect of inheritance is that the child class (or subclass or derived class) has the following characteristics:
·        Automatically has all the member variable declarations of the parent class.
·        Automatically has all the same member functions as the parent, which (by default) will work the same way as those functions do in the parent.

<?php

class   parent1

{

var $name="test";
var $phone="123456";

public function disp()
{

echo $this->name;
echo "<br>";
echo $this->phone;

echo "<br>";

}
}

class   inheritance1  extends parent1
{

function read()
{

echo "it is working fine";

}


}

$obj=new   inheritance1();

$obj->disp();

$obj->read();


?>


 How to call parent class   constructor     parent::__construct();   :
<?php
class BaseClass {
   function __construct() {
       print "In BaseClass constructor\n";
   }
}

class SubClass extends BaseClass {
   function __construct()
   {
       parent::__construct();
       print "In SubClass constructor\n";
   }
}

//$obj = new BaseClass();
$obj = new SubClass();
?>


Function     Overriding  :

 

Function definitions in child classes override definitions with the same name in parent classes. In a child class, we can modify the definition of a function inherited from parent class.

<?php
class abc
{
var $a;
var $b;
function cal($p,$q)
{
$this->a=$p;
$this->b=$q;
$sum=$this->a+$this->b;
echo"it is addition of two parameters".$sum;
}
}
class xyz extends abc
{
var $a;
var $b;
var $c;
var $d;
function cal($p,$q)
{
$this->a=$p;
$this->b=$q;

$sum=$this->a*$this->b;
echo"multiplication of two parameters".$sum;
}

}
$obj=new xyz();
$obj->cal(5,2);

?>



Function    Overloading   using    function __call :

<?php

 

class test12

 

{

    public function __call($name, $arguments)

               

    {

        if ($name === 'test'){

            if(count($arguments) === 1 ){

                return $this->test1($arguments[0]);

            }

            if(count($arguments) === 2){

                return $this->test2($arguments[0], $arguments[1]);

            }

                                                if(count($arguments) === 3){

                return $this->test3($arguments[0], $arguments[1],$arguments[2]);

            }

 

        }

    }

 

    private function test1($data1)

    {

       echo $data1;

    }

 

    private function test2($data1,$data2)

    {

       echo $data1.' '.$data2;

    }

                 private function test3($data1,$data2,$data3)

    {

       echo $data1.' '.$data2.$data3;

    }

}

 

$test = new test12();

 

$test->test('one argument');                //echoes "one argument"

 

$test->test('two','arguments');

 

$test->test('three','om','test');          //echoes "two arguments"

 

 

?>

 

Public Members   :

 

Unless you specify otherwise, properties and methods of a class are public. That is to say, they may be accessed in three possible situations:
·        From outside the class in which it is declared
·        From within the class in which it is declared
·        From within another class that implements the class in which it is declared
Till now we have seen all members as public members. If you wish to   limit   the   accessibility    of    the    members   of   a   class   then    you    define   class      members    as    private.
<?php
class  books
{

var  $bookname;
var  $price;

function display($name, $cost)
{
echo $this->bookname=$name;
echo '<br>';
echo $this->price=$cost;
echo '<br>';

}
}

$obj=new books();
$obj->display("om",10);
?>

Interfaces   :

 

Interfaces are defined to provide a common function names to the implementors. Different implementors can implement those interfaces according to theri requirements. You can say, interfaces are skeltons which are implemented by developers.
As of PHP5, it is possible to define an interface, like   this  :

interface Mail {
   public function sendMail();
}

Then, if another class implemented that interface, like   this :

class Report implements Mail {
   // sendMail() Definition goes here
}
Example :
<?php

interface  test

{

function disp();

}

class  hello implements test
{


function disp()
{


echo "it is interface function";


}


}

$obj=new  hello();


$obj->disp();


?>

Constants   :


A constant is somewhat like a variable, in that it holds a value, but is really more like a function because a constant is immutable. Once you declare a constant, it does not change.
Declaring one constant is easy, as is done in this version of   MyClass  :
Php  constant example   using  define() :

<?php
define("PI","3.142");
$r=2;
echo $area=$r*$r*PI;
?>

Php   constant  example using   “const” :

<?php

class calarea

{

    const PI="3.142";
                var $r=2;



    function area()
                {
                echo $this->r*$this->r*self::PI;
    }

}


$class = new calarea();

$class->area();


?>





Class      Constants  :

It is possible to define constant values on a per-class basis remaining the same and unchangeable. Constants differ from normal variables in that you don't use the $ symbol to declare or use them. Like static members, constant values cannot be accessed from an instance of the object (using $object::constant).
The value must be a constant expression, not (for example) a variable, a class member, result of a mathematical operation or a function call.
Example : Defining and using a constant
<?php
class MyClass
{
    const constant = 'constant value';
 
    function showConstant() {
        echo  self::constant . "\n";
    }
}
 
echo MyClass::constant . "\n";
 
$class = new MyClass();
$class->showConstant();
// echo $class::constant;  is not allowed
?>


Abstract   Classes  :

An abstract class is one that cannot be instantiated, only inherited. You declare an abstract class with the keyword abstract, like this :
When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same visibillity.

abstract class MyAbstractClass {
   abstract function myAbstractFunction() {
   }
}
Example :
<?php

abstract        class       Animal
{
    public $name;
    public $age;
   
    public function Describe()
    {
        return $this->name . ", " . $this->age . " years old";   
    }
   
    abstract public function Greet();
}

class Dog extends Animal
{
    public function Greet()
    {
        return "Woof!";   
    }
   
   
}

$animal = new Dog();
$animal->name = "Bob";
$animal->age = 7;
echo $animal->Describe();
echo $animal->Greet();

?>

Static         Keyword    :   

 

Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static   can   not   be accessed with an instantiated class object (though a static method can).
Example :
<?php

Class  staticexample
{

public   static   $name="om";           // static variable


public static function disp()      //static member function


{

echo "static member function is this";


}


}


$obj=new   staticexample();


print  staticexample::$name;       // accessing static variable

echo "<br>";

staticexample::disp();            //accessing static member function





?>

Final    Keyword   :


PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
Following example results in Fatal error: Cannot override final method BaseClass::moreTesting()
<?php
class BaseClass {
   public function test() {
       echo "BaseClass::test() called<br>";
   }
  
   final public function moreTesting() {
       echo "BaseClass::moreTesting() called<br>";
   }
}
 
class ChildClass extends BaseClass {
   public function moreTesting() {
       echo "ChildClass::moreTesting() called<br>";
   }
}
?>

Parent    keyword   :
<?php
class A
{
    function example()
           {

        echo "I am A::example() and provide basic functionality.<br />\n";
    }
}

class B extends A  {
    function example() {
        echo "I am B::example() and provide additional functionality.<br />\n";
        parent::example();
    }
}

$b =new B;


// This will call B::example(),    which will in turn call A::example().


$b->example();

?>

SOME EXAMPLES TO USE OBJECT ORIENTED  PROGRAMMING IN PHP FOR INSERT,UPDATE ,DELETE ,SEARCH & DISPLAY RECORD:


(1)create table example:

create table example
(id int,
name  varchar(200));


(2)write code for     “ connect.php ”  :

<?php
class db
{
var $host='localhost';
var $username='root';
var $password='';
var $connection;
var $database;
function __construct()
{
$this->connection=mysql_connect($this->host,$this->username,$this->password);
if($this->connection)
{
Echo   "connection successful";
echo    "<br>";
}
else
{
echo"connection error";
echo"<br>";
}
}
}
$obj=new db();
?>

(2)write code for   form.html:

<form action=”insert.php “  method=”post”>
Id<input type=text      name=id>
Name <input type=text     name=name>
</form>


 (3)write  code   for    “insert.php”    :

<?php

Class  db
{
var $host="localhost";
var $username="root";
var $password="";
var $database="amrapali";
var $connection;
function __construct()
{
$this->connection=mysql_connect($this->host,$this->username,$this->password);
if($this->connection)
{
echo"connected successfully";
}
else
{
echo"connection failed";
}
mysql_select_db($this->database,$this->connection);
}

function  insert()
{
$id=$_POST[‘id’];
$name=$_POST['name'];
$sql="insert   into   example(id,name) values(‘$id’,’$name’)";
mysql_query($sql);
}
}
$obj=new db();
$obj->insert();
?>


(4)  write code for  updateform.html   :

<form action=”update.php “      method=”post”>
Id<input type=text      name=id>
Name <input type=text     name=name>
</form>

(5)write  code  update.php  :

<?php

class   db
{

var $host="localhost";
var $username="root";
var $password="";
var $database="amrapali";
var $connection;
function __construct()

{

$this->connection=mysql_connect($this->host,$this->username,$this->password);
if($this->connection)
{

echo"connected successfully";

}
else
{
echo"connection failed";
}
mysql_select_db($this->database,$this->connection);
}

function   update()
{
$id=$_POST[‘id’];
$name=$_POST['name'];
$sql="update example    set   id='$id'   where name='$name' ";
mysql_query($sql);

}

}
$obj=new db();
$obj->update();
?>

(6)Write   code   for   “delete.html” file   :

<form action=”delete.php “      method=”post”>

Id<input type=text      name=id>
</form>


(7)write    code for  "delete.php" file  :

<?php
class db
{
var $host="localhost";
var $username="root";
var $password="";
var $database="amrapali";
var $connection;
function __construct()
{
$this->connection=mysql_connect($this->host,$this->username,$this->password);
if($this->connection)
{
echo"connected successfully";
}
else
{
echo"connection failed";
}
mysql_select_db($this->database,$this->connection);
}
function delete()
{
$id=$_POST["id"];
$sql="delete from example where id='$id'";
mysql_query($sql);
}
}
$obj=new db();
$obj->delete();
?>


(7)write code for display form table record:

<?php
class db
{
var $host="localhost";
var $username="root";
var $password="";
var $database="amrapali";
var $connection;
function __construct()
{
$this->connection=mysql_connect($this->host,$this->username,$this->password);
if($this->connection)
{
echo"connected successfully";
}
else
{
echo"connection failed";
}
mysql_select_db($this->database,$this->connection);
}
function display()
{
$sql="select * from example";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
echo $row['id'];
echo $row['name'];
echo"<br>";
}
}
}
$obj=new db();
$obj->display();
?>




Ajax   with    PHP  &  MYSQL   Database :



PHP  Ajax :

What is AJAX ?.....

AJAX stands for Asynchronous JavaScript and  XML.

AJAX is a new technique for creating better, faster, and...

more interactive web applications with the help of XML, HTML, CSS and Java Script.

Conventional web application trasmit information to and from the sever using synchronous requests.

This means you fill out a form,

hit submit,and get directed to a new page with new information from the server.

With AJAX when submit is pressed, JavaScript will make a request to the server,

interpret the results and update the current screen. In the purest sense,



the user would never know that anything was even transmitted to the server.

FIRST CREATE  TABLE    details :
create table  details
(id  int,
name   varchar(200),
city    varchar(200));



Ajax example code  for   inserting record from  form   to MYSQL  Database :


(1)first write code for  insert.html   file:
<html>
<head>
<script>
function ajax_post()
{
    // Create our XMLHttpRequest object
    var hr = new XMLHttpRequest();
     
    // Create some variables we need to send to our PHP file
     
    var url = "insert.php";
     
    var id = document.getElementById("id").value;
     
    var nm = document.getElementById("name").value;
     
      var cy = document.getElementById("city").value;
     

     

    var vars = "id="+id+"&name="+nm+"&city="+cy;
     
    hr.open("POST", url, true);
    // Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function() {
          if(hr.readyState == 4 && hr.status == 200) {
                      var return_data = hr.responseText;
                              document.getElementById("status").innerHTML = return_data;
          }
    }
    // Send the data to PHP now... and wait for response to update the status div
    hr.send(vars); // Actually execute the request
    document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<input type="text" id="id" name="id">
<input type="text" id="name" name="name">
<input type="text" id="city" name="city">
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();">
<div id="status"></div>
</body>
</html>


(2)Then    write    code   for     insert.php   :
<?php
$id=$_POST['id'];
$nm=$_POST['name'];
$cy=$_POST['city'];
$con=mysql_connect('localhost','root','' );
mysql_select_db('needa',$con);
$sql="insert into details (id,name,city) values('$id','$nm','$cy')";
mysql_query($sql);
echo "record inserted successfully";


?>

Ajax example code   to   update record   from    form   to MYSQL   Database   :
(1) write   code for    update.html  :
<html>
<head>
<script>
function ajax_post()
{
    // Create our XMLHttpRequest object
    var hr = new XMLHttpRequest();
     
    // Create some variables we need to send to our PHP file
     
    var url = "update.php";
     
    var id = document.getElementById("id").value;
     
    var nm = document.getElementById("name").value;
     
      var cy = document.getElementById("city").value;
     

     

    var vars = "id="+id+"&name="+nm+"&city="+cy;
     
    hr.open("POST", url, true);
    // Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function() {
          if(hr.readyState == 4 && hr.status == 200) {
                      var return_data = hr.responseText;
                              document.getElementById("status").innerHTML = return_data;
          }
    }
    // Send the data to PHP now... and wait for response to update the status div
    hr.send(vars); // Actually execute the request
    document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<input type="text" id="id" name="id">
<input type="text" id="name" name="name">
<input type="text" id="city" name="city">
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();">
<div id="status"></div>
</body>
</html>
(2)write    code   for   update.php  :
<?php
$id=$_POST['id'];
$nm=$_POST['name'];
$cy=$_POST['city'];
$con=mysql_connect('localhost','root','' );
mysql_select_db('needa',$con);
$sql="update details set name ='$nm', city='$cy' where id='$id'";
mysql_query($sql);
echo "record updated successfully";

?>



Ajax example code   to   search record   from       MYSQL   Database   :
(1)write   code search.html :
<html>
<head>
<script>
function ajax_post()
{
    // Create our XMLHttpRequest object
    var hr = new XMLHttpRequest();
           
    // Create some variables we need to send to our PHP file
           
    var url = "search.php";
           

           
    var nm = document.getElementById("name").value;
           

           

           

    var vars = "name="+nm;
           
    hr.open("POST", url, true);
    // Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function() {
                if(hr.readyState == 4 && hr.status == 200) {
                            var return_data = hr.responseText;
                                    document.getElementById("status").innerHTML = return_data;
                }
    }
    // Send the data to PHP now... and wait for response to update the status div
    hr.send(vars); // Actually execute the request
    document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<input type="text" id="name" name="name">
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();">
<div id="status"></div>
</body>
</html>


(2)write  code for search.php:
<?php
$nm=$_POST['name'];
$con=mysql_connect('localhost','root','' );
mysql_select_db('needa',$con);
$sql="select * from details where name='$nm'";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
echo $row['id'];
echo $row['name'];
echo $row['city'];

}
?>







Ajax example code   to     Delete    record   from       MYSQL   Database   :
(1)write    code   for   delete.html  :
<html>
<head>
<script>
function ajax_post()
{
    // Create our XMLHttpRequest object
    var hr = new XMLHttpRequest();
           
    // Create some variables we need to send to our PHP file
           
    var url = "delete.php";
           
    var id = document.getElementById("id").value;
           
    var vars = "id="+id;
           
    hr.open("POST", url, true);
    // Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function() {
                if(hr.readyState == 4 && hr.status == 200) {
                            var return_data = hr.responseText;
                                    document.getElementById("status").innerHTML = return_data;
                }
    }
    // Send the data to PHP now... and wait for response to update the status div
    hr.send(vars); // Actually execute the request
    document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<input type="text" id="id" name="id">
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();">
<div id="status"></div>
</body>
</html>


(2) write  code for   delete.php  :

<?php
$id=$_POST['id'];
$con=mysql_connect('localhost','root','' );
mysql_select_db('needa',$con);
$sql="delete from details where id='$id'";
mysql_query($sql);
echo "record deleted successfully";

?>


(1)FIRST WRITE javascript CODE in <head> section </head> :
<html>
 <head>

<script type="text/javascript">
function doDelete(id){
if(confirm("Do you want to delete the record?")){
$.ajax({
url:'delete.php',
type:'post',
data:'id='+id,
success:function(msg){
alert(msg);
window.location.href='pagination2.php';
}
});
}
}
</script>

</head>

<!---Second  use  following line where you want to call doDelete() method in <body> section </body>--->
<body>
<?php

   include("connect.php");
  
    $per_page = 8;

    $pages_query = mysql_query("SELECT COUNT('id') FROM  notes order by coursename,semester ASC");

    $pages = ceil(mysql_result($pages_query, 0) / $per_page);

   
    $page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
    $start = ($page - 1) * $per_page;
   
    $query = mysql_query("SELECT *  FROM notes LIMIT $start, $per_page");

while($row = mysql_fetch_assoc($query))


{

echo "record one";

?>



<a class="click-more" href="#" onClick="doDelete('<?php echo $row['id']; ?>');">read more</a>


<?php




$prev = $page - 1;
    $next = $page + 1;
   
    if(!($page<=1)){
        echo "<a href='pagination1.php?page=$prev'><button>Prev</button></a> ";
    }

    if($pages>=1 && $page<=$pages){
   
        for($x=1;$x<=$pages;$x++){
            echo ($x == $page) ? '<strong><a href="?page='.$x.'"><button>'.$x.'</button></a></strong> ' : '<a href="?page='.$x.'"><button>'.$x.'</button></a> ';
       
        }
   
    }
   
    if(!($page>=$pages)){
        echo "<a href='pagination1.php?page=$next'><button>Next>></button></a>";
    }
   
   
?>

</body>
</html>


(2)write code for "delete.php" file:

<?php

$id=$_POST['id'];

include("connect.php");


$sql="delete from notes where id='$id'";

mysql_query($sql) or die(mysql_error());


echo "Record deleted successfully";

echo '<br></br>';

echo '<a href="pagination1.php"><button>back to previous page</button></a>';


?>



Written by

We are Creative Blogger Theme Wavers which provides user friendly, effective and easy to use themes. Each support has free and providing HD support screen casting.

0 comments:

Post a Comment

PHP Training Mumbai, PHP MySQL Training Mumbai, PHP Course Mumbai, PHP Institute Mumbai

 

© 2013 PHP TRAINING IN MUMBAI BY OM SIR . All rights resevered. Designed by OM SIR

Back To Top