PHP-Walk In Interview Pune-Softbridge Solutions

PHP- Walk-In Interview Pune - softbridge Solutions

Job Description:
Previous experience as an Analyst Programmer in a PHP/Joomla LAMP environment.
Experience on Social Networking / E-Learning Platform.
Excellent knowledge of PHP/MySql applications.
Strong SQL Server and relational database design experience.
Knowledge of system analysis and design, including object orientated analysis and design skills.

Skills:
JQuery/ JavaScript / PHPScript
Payment Gateway
Search Engine
HTML/ CSS
Frameworks: Code igniter/ Moodle/ Zend/ MVC/ Smarty
Facebook Integration/ Tweeter Integration

Experience: 2 - 5 years

please check below link to view complete details:
PHP- Walk-In Interview Pune - softbridge Solutions


Bookmark and Share

cURL Simple Example in PHP

cURL Simple Example in PHP:


cURL allows you to connect and communicate to many different types of servers with many different types of protocols.
PHP Supports libcurl.

Example:

<?php
        // initialize curl session
        $ch = curl_init();
       
        curl_setopt($ch, CURLOPT_URL, "example.com");  // set url      
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//return the transfer as a string
        
        $output = curl_exec($ch);//output string


        // close curl session
        curl_close($ch);     
?>


Bookmark and Share

What is cURL in PHP?

What is cURL in PHP?

cURL allows you to connect and communicate to many different types of servers with many different types of protocols.
PHP Supports libcurl.

Requirements:
In order to use PHP's cURL functions you need to install the libcurl package.PHP 5.0.0 requires a libcurl version 7.10.5 or greater.

cURL Functions:
    curl_close : Close a cURL session.
    curl_errno: Return the last error number.
    curl_error: Return a string containing the last error for the current session.
    curl_exec: Perform a cURL session.
    curl_getinfo: Get information regarding a specific transfer.
    curl_init: Initialize a cURL session.
    curl_setopt_array: Set multiple options for a cURL transfer.
    curl_setopt: Set an option for a cURL transfer.
    curl_version: Gets cURL version information.


Bookmark and Share

Difference between Cookies and Session in PHP

Difference between Cookies and Session in PHP
  • Cookies are stored in the user’s browser memory.A cookie can keep information in the user's browser until deleted.
  • Session : logical object that allows you to preserve data across subsequent http requests.Whenever PHP creates a new session, it generates a session ID.
  • Session values are store in server side not in user’s machine. A session is available as long as the browser is opened. User couldn't be disabled the session. 
  • Cookies are stored in client side and sessions are stored in server side
  • Cookies can only store strings.We could store not only strings but also objects in session.
  • we could be save cookie for future reference, but session couldn't. When users close their browser, they also lost the session.


Bookmark and Share

Difference between Get and post method

What is the difference between Get and post method.
  • Get method is not secure as data will be appeared in the url address.
  •  Using post method is much secure as  it will not appear in the url address.
  • Get Method transfers only 255 char. No limitation for the Post method 
  • Get request is comparatively faster.
  • Get is the default method of the HTML From elememt.we need to specify the method attribute and give it the value "POST".
  • If you use POST method than all the form element value is passed from the header response. which we can get it using the $_POST method.
  • If you use GET method ,we can get it using the $_GET method.
  • You can only bookmark if the method used is GET and cannot bookmark in POST method.
  • GET request is sent via URL, so GET can carry only text data whereas POST has no such restriction and it can carry both text as well as binary data.
  • GET requests are restricted to use ASCII characters only whereas POST requests can use the 'enctype' attribute with a value "multipart/form-data".


Bookmark and Share

How many ways you can delete a session variable?

How many ways you can delete a session variable?

In order to kill the session variable use:
  1. unset($_SESSION["test"]);
  2. session_destroy() — Destroys all data registered to a session
  3. session_unregister() — Unregister a global variable from the current session.
  4. session_unset() — Free all session variables.
To use the session variables again, session_start() has to be called.


Bookmark and Share

Difference between array_slice and array_splice in php

Difference between array_slice() and array_splice() in php
array_splice() is used to remove some elements from an array and replace with specified elements.
array_slice() is used to extract a selected parts of an array .

array_slice() Function in PHP:

array_slice() is used to extract a selected parts of an array .

array_slice() Example:
<?php
$numbers = array("1", "2", "3", "4", "5");
$new_numbers = array_slice($numbers, 2);      
$new_numbers = array_slice($numbers, -3, 1);  
?>
Output:
Array
(
    [0] => 3
    [1] => 4
    [2] => 5
)
Array
(
    [0] => 3
    
)


Bookmark and Share

How To Remove Html Tags from String in Php

How To Remove Html Tags From String In Php
In this article,I will explain how to remove Html tags from string with php.In php we are using strip_tags function to strip HTML and php tags.
strip_tags function returns a string with HTML and PHP tags stripped from a given string.

strip_tags Syntax:
strip_tags(string $string,string $allowable_tags);


Bookmark and Share

Difference between include and include_once in php

Difference between include and include_once in php
All these functions include and include_once are used to include the files in the php page.


PHP include() Function:
If the specified file is not available ,the include() function generates a warning,and executes the
remaining code.

Example:
<?php 
include("test.php"); 
?>


Bookmark and Share

Difference between php5 and php6

Difference between php5 and php6
In this article, I will explain about upcoming changes in php6.php6 is not yet released.PHP6 will offer many improvements and will remove some of the functionality that has been in older versions of PHP.


Bookmark and Share

Difference between php4 and php5


Difference between php4 and php5 

PHP5 introduces many new features, I have mentioned some of them:

Unified Constructors and Destructors:
In PHP4, constructors had same name as the class name. In PHP5, you have to name your constructors as  __construct() and  destructors as __destruct().


Bookmark and Share

Difference between mysql4 and mysql5

Difference between mysql4 and mysql5 

MySQL 5 introduced new important features
1. Cursors
2. Triggers
3. Stored Procedures
4. Views


Bookmark and Share

How to delete file in PHP

How to delete file in PHP:
In this article,I will explain how to delete file using php unlink function with sample example.

unlink: Deletes a file


Bookmark and Share

Difference between mysql_fetch_object and mysql_fetch_array in PHP

difference between mysql_fetch_object and mysql_fetch_array in PHP

mysql_fetch_object :
mysql_fetch_object returns the results from database as objects.(fetches a result row as object)
$result->email


Bookmark and Share

chdir function in php


chdir function in php

The chdir() function changes the current directory to the other directory.

chdir() Syntax:
chdir(string $directory) 

chdir example:
<?php
getcwd();//current directory (e.g.c:\project)
chdir("files");//changes to files directory
echo $current_directory=getcwd();
?> 

Output: C:\project\files


Bookmark and Share

Difference between join and implode in php.


Difference between join and implode in php. 
In this example, I will show how to use join and implode in php.

Join : Join is an Alias of implode().

Example:
<?php
$arr = array('Rajesh', 'India', 'Tutorials');
$str = join(",", $arr);
echo $str; 
?>
Output: Rajesh,India,Tutorials.

implode: implode Returns a string from array elements.

Example:
<?php
$arr = array('Rajesh', 'India', 'Tutorials');
$str = implode(",", $arr);
echo $str; 
?>
Output:Rajesh,India,Tutorials.


Bookmark and Share

Check password length in php


Check password length in php

I have written function to check password length in php

<?php
$password="checkpassword";


$passwordCheck=passwordLength($passwod);


function passwordLength($pwd)
{
    $pwdlen=strlen($pwd);//calculate length of password using strlen function


      if($pwdlen<=4) //if length of password is less than 4 then password is too short.
      {
         return "Password too short!";
      }
    else if ($pwdlen>16) //if length of password is greater than 16 then password is too Long.
   {
         return "Password too Long!";
     }



?>


Bookmark and Share

Regular expression Basics in php

Regular expression Basics in php:
In this article ,i will show how to use regular expressions in php.

 \char escape char

  .            Any single character

 [chars]       One of following chars

 [^chars]      None of following chars

 text1|text2   text1 or text2

 ? 0 or 1 of the preceding text

 * 0 or N of the preceding text  (hungry)

 + 1 or N of the preceding text

 Example: (.+)\.html? matches test.htm and test.html

 (text)  Grouping of text

 Example:  ^(.*)\.html foo.php?bar=$1

  ^    Start of line anchor

  $    End   of line anchor

 Example: ^test(.*) matches test and test1 but not ttest
  (.*)1$ matches a1 and b1, but not test


Bookmark and Share

.htaccess file and URL rewrite rule in php


.htaccess file and URL rewrite rule in php

Redirect URLs using .htaccess  :   
You can use .htaccess to redirect users to a different URL(redirect a url)    
Sometimes you need to redirect some URL and/or page on your site to another one.    
using the “Redirect” directive:    
   
Redirect /folder http://www.example.com/newfolder      
   
Another useful directive is the RedirectMatch    
   
RedirectMatch "\.html$" http://www.example.com/index.php      
   
This will redirect all requests to files that end with .html to the index.php file.      
One of the more powerful tricks of the .htaccess hacker is the ability to rewrite URLs    
   
simple rewriting        
all requests to whatever.htm will be sent to whatever.php:    
Options +FollowSymlinks      
RewriteEngine on      
RewriteRule ^(.*)\.htm$ $1.php [NC]      
RewriteRule ^menu.html menu.php      


Bookmark and Share

Difference between strpos and stripos in php

Difference between strpos and stripos in php


strpos()Function in PHP:


strpos():Returns the position of the first occurrence of a substring in a string.
If the string is not found, this function returns FALSE.

Strpos Syntax:
strpos(string,search,start)

Strpos() function example in php:
<?php
$phpString = 'strpos function in php';
$search   = 'function';
$position = strpos($phpString, $search);


if ($position !== false)
{
     echo "Found at position $position";
}
 else
{
     echo "Not Found";
}
?>

stripos() Function in PHP:


The stripos() function is case-insensitive.
stripos():Returns the position of the first occurrence of a case-insensitive substring in a string.
If the string is not found, this function returns FALSE.

stripos Syntax:
stripos(string,search,start)

stripos () function example in php:
<?php
$phpString = 'strpos function in php';
$search   = 'Function';
$position = stripos($phpString, $search);


if ($position !== false)
{
     echo "Found at position $position";
}
 else
{
     echo "Not Found";
}
?>

Difference between strpos and stripos in php:
  1. stripos works in php5, strpos in php4 and php5.
  2. Unlike the strpos(), stripos() is case-insensitive.



Bookmark and Share

Ob_start() Function -Tutorials and Examples in Php5

Ob_start() function- Tutorials,Examples in Php5


ob_start Function is used to turn on output buffering.The PHP output buffering will save all the server outputs to a string variable.it  returns TRUE on success or FALSE on failure.
If you are using ob_start, then you should also use ob_end_flush  function for flushing the output buffer.

Ob_start() and ob_end_flush()  Example:

<?php
function changeColor($buffer)
{
  return (str_replace("Blue", "Red", $buffer));
}
//ob_start() function in PHP5
ob_start("changeColor");
?>
<html>
<tile>Ob_start() funtion Tutorials,Examples in Php5</title>
<body>
<span>Blue Car</span>
</body>
</html>
<?php
//ob_end_flush() function in PHP5
ob_end_flush();
?>
Output:
<html>
<tile>Ob_start() funtion Tutorials,Examples in Php5</title>
<body>
<span>Red Car</span>
</body>
</html>

Ob_start() and ob_get_clean()  Example:

<?php 
ob_start();
 ?>
<html>
<tile>Ob_start() funtion Tutorials,Examples in Php5</title>
<body>
<span>Blue Car</span>
</body>
</html>
<?php
 $code = ob_get_clean();
?>

Output:
<html>
<tile>Ob_start() funtion Tutorials,Examples in Php5</title>
<body>
<span>Blue Car</span>
</body>
</html>


Bookmark and Share

How To Send Mail with Attachment in PHP

How To Send Mail with Attachment in PHP
I this tutorial,I will explain how to send mail with attachments in PHP.
you can send attachments using a multipart/mixed content header.then convert the attachment into a base64 string.We are  creating a very simple script with php.
the script sends an email to that address with a pdf file(attached file)that I specify in the script.

Here's a simple php example of sending html mail with attached file:

ExampleHow To Send Mail with Attachment in PHP
<?php
$file_path="files/test.pdf";//// Path to the file 
$file_path_type = "application/pdf"; 
$subject = "Testing File attachment"; 

$headers = "From: ".$from. "\r\n" .
"CC: php@example.com";
$from ="test@example.com"; //From email.
$message = "Hello!!<br>";
$to ="rajesh@example.com"; //To email
$file_path_name="test.pdf";

$file = fopen($file_path,'rb');
$data = fread($file,filesize($file_path));
fclose($file);
$semi_rand = md5(time());

$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

//Headers
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";

$message .= "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message .= "\n\n";

//convert the attachment into a base64 string
$data = chunk_split(base64_encode($data));

$message .= "--{$mime_boundary}\n" .
"Content-Type: {$file_path_type};\n" .
" name=\"{$file_path_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data .= "\n\n" .
"--{$mime_boundary}--\n";

$sent = @mail($to, $subject, $message, $headers);

if($sent) {
echo "Sent Succesfully";

} else {
die("Email not Delivered");
}

?>

I hope this will help you to send email with attachments in PHP.


Bookmark and Share

How to Send Email from a PHP Script using mail() function

How to Send Email from a PHP Script using mail() function.



In this article, I will show you how to send  mail using PHP mail() function in PHP.


PHP mail() function:

The PHP mail() function is used to send emails in php.


Syntax :
mail(string to, string subject, string message, string headers,parameters);


to:  The receiver of the email
subject: The subject of the email.
message: the body of the email.
headers: Additional headers, like From, Cc, and Bcc.


Example:


<?php
$to = "rajesh@example.com";//The receiver of the email
$subject = "Test mail"; //The subject of the email.
$body = "Hello!"; //The body of the email.
$from = "test@example.com";
$headers = "From:" . $from; 
//mail() function
if(mail($to,$subject,$message,$headers)) 
{
   echo("Message successfully sent!");
}
else
{
  echo("Message delivery failed...");
}
?> 


Bookmark and Share

PHP implode() Function


PHP implode() Function


implode : The implode() function returns a string from the elements of an array.


Syntax
implode(separator,array)


Example: implode() 


<?php
$arr = array("PHP","implode","explode" ,"string","functions");
$str = implode(",", $arr);
echo $str; 
?>


OutputPHP, implode, explode, string, functions.


Bookmark and Share

PHP explode() Function


PHP explode() Function


explode :- The explode() function split a string into an array.

Syntax
explode(separator,string)


Note: Separator cannot be an empty string

Example: explode()

<?php


$name= "PHP implode explode string functions";
$arr = (" ", $name);
print_r($arr);
?>


Output:
array([0]=>"PHP",[1]=>"implode",[2]=>"explode",[3]=>"string",[4]=>"functions");


Bookmark and Share

PHP Simple programs


Let us begin with a very simple PHP program. 

Example:

hello.php
<?php
echo "Hello!!.";
?>
Output:Hello!!.


Example Using HTML and PHP
hello.php


<html> 
<head><title>My First PHP Page</title></head> 
<body> 
<span>
<?php 
   $name="Rajesh";
   echo "Hello $name";
?>
</span> 
</body> 
</html> 


Output:Hello Rajesh


Bookmark and Share

Difference between strstr and stristr in php


Difference between strstr and stristr in php.

strstr() and stristr both are used to find the first occurence of the string but stristr( ) is case insensitive.

strstr() - Find first occurrence of a string
Syntax:
strstr ($string, string)  

Example:

<?php
$email = 'rajesh@tEst.com';
$domain_name = strstr($email, 'E');
echo $domain_name; 


?>


Output:Est.com

stristr() - Find first occurrence of a string (Case-insensitive)
Syntax:
stristr ($string, string)  

Example:
<?php
$email = 'rajesh@tEst.com';
$domain_name = stristr($email, 'E');
echo $domain_name; 


?>
Output: esh@tEst.com


Bookmark and Share

Difference between in_array() and array_search() in php?

Difference between in_array() and array_search() in php?
In this tutorial,we will study difference between in_array and array_search.

in_array : -Checks if a value exists in an array
array_search() :-searches an array for a given value and returns the  corresponding key if successful.

in_array Syntax:
in_array(search value, array , strict Boolean);
search value:- will be the value to search in an array
array: will the array to search
strict Boolean: is optional.

Example:

<?php
$name = array("Rajesh", "Sharma", "PHP", "Linux");
if (in_array("Rajesh", $name)) 
{
    echo "Yes";
}
else
{
echo "False";
}
?>

Output: Yes

array_search() :-searches an array for a given value and returns the  corresponding key if successful.

Syntax:
array_search()(search value, array , strict Boolean);
search value:- will be the value to search in an array
array: will the array to search
strict Boolean: is optional.

Example:

<?php
$name = array(0=>"Rajesh", 1=>"Sharma", 2=>"PHP", 3=>"Linux");
echo $key = array_search("Rajesh", $name);

?>
Output: 0


Bookmark and Share

A .htaccess rule that will divert any page in another folder

A .htaccess rule that will divert any page in another folder


1)If you want to redirect http://test.com/f1/  to  http://test.com/f2/.
 .htaccess file will be.

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^f1.*$ http://test.com/f2/ [R=301,L]


2)If you want to redirect http://test.com/f1/test.html to http://test.com/f2/test.html.
 .htaccess file will be.

Options +FollowSymLinks
RewriteEngine On
RewriteRule RewriteRule ^f1/(.*)$ http://test.com/f2/$1 [R=301,L]

3) If you want to redirect http://test.com/ to http://www.test.com/.
 .htaccess file will be.


Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^test.com [NC]
RewriteRule ^(.*)$ http://www.test.com/$1 [R=301,L]

4) If you want to redirect  http://test.com/ to https://test.com/.

 .htaccess file will be.
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.test.com/$1 [R,L]


Bookmark and Share

urlencode and urldecode in php

urlencode :-Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs.

Syntax:
string urlencode ( string $str );

Example:
<?php
$url="Rajesh SharmaTutorials";
$encodeUrl=urlencode($url);
echo '<a href="test.php?sample=$encodeUrl">';
?>

Output: <a href="test.php?sample=Rajesh+Sharma+Tutorials">

urldecode :- Returns the decoded string.(Returns the original string of the input URL).

<?php
$sample=$_GET["sample"];
 echo $sample=urldecode($sample);
?>

Output:Rajesh SharmaTutorials


Bookmark and Share

persistent cookie in php


persistent cookie in php:

A persistent cookie is a cookie which is stored in a cookie file permanently on the browser's computer.
  • Content of a Persistent cookie remains unchanged even when the browser is closed.
  • Persistent cookies are less secure because users can open cookie files see the cookie values.
  • Persistent cookies can be used for tracking long-term information. 
Setting cookie in php:
Cookies in PHP can be set using the setcookie() function

Syntax:
Setcookie(name, value, expire, path, domain);

Example:
<?php
Setcookie(“Full Name”, “Rajesh Sharma”, time()+3600);
?>




Bookmark and Share

Polymorphism in OOP

Polymorphism in OOP:


In this tutorial we will study about polymorphism.
  • Polymorphism in PHP5 : To allow a class member to perform diffrent tasks.
  • polymorphism where the function to be called is detected based on the class object calling it at runtime.

Example:
< ?
class Person
{
    public function Talk()
    {
         echo "English";
    }
}

class Language extends Person
{
      public function Talk()
      {
           echo "French";
      }


}

function CallMethod(Person $p)
{
      $p->Talk();
}



$l = new Language();
CallMethod($l);
?>


Output:
French;


Bookmark and Share

Inheritance in OOP

Inheritance in OOP :

In this tutorial we will study about Inheritance.
  • Inheritance is a mechanism of extending an existing class.
  • In Inheritance child class inherits all the functionality of Parent Class.

For example, when you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods.

<?php


class BaseClass
{
    public function GetValue($string)
    {
        echo 'BaseClass:'. $string ;
    }


    public function setValue($string)
    {
        echo  $string;
    }


    
}


class ChildClass extends BaseClass
{
    public function GetValue($string)
    {
        echo 'ChildClass:'. $string ;
    }
}


$b = new BaseClass();
$c = new ChildClass();


$b->GetValue('Rajesh Test'); // Output: 'BaseClass: Rajesh Test'
$b->setValue('Rajesh Test'); // Output: 'Rajesh Test'
$c->GetValue('Rajesh Tutorials'); // Output:'ChildClass: Rajesh Tutorials'
$c->setValue('Rajesh Test'); // Output: 'Rajesh Test'


?>


Bookmark and Share

Serialization and UnSerialization in PHP

Serialization/UnSerialization:

  • Generates a storable representation of a value.
  • serialize() returns a string containing a byte-stream representation of any value that can be stored in PHP. 
  • unserialize() can use this string to recreate the original variable values.
  • This process makes a storable representation of a value that is useful for storing or passing PHP values.
  • To make the serialized string into a PHP value again, use unserialize().

Before starting your serialization process, PHP will execute the __sleep function automatically. This is a magic function or method.
Before starting your unserialization process, PHP will execute the __wakeup function automatically. This is a magic function or method.


What can you Serialize and Unserialize?
  • Variables
  • Arrays
  • Objects 
What cannot you Serialize and Unserialize?
  • Resource-type
Example:
//BaseClass.php
<?php

  class BaseClass {
      public $var = 100;
    
      public function show() {
          echo $this->var;
      }
  }
  
// test1.php:


  include("BaseClass.php");
  
  $a = new A;
  $v = serialize($a);
  file_put_contents('store_in_var', $v);


// page2.php:
  
  include("BaseClass.php");
  $v = file_get_contents('store_in_var');
  $a = unserialize($v);




  $a->show();
?>

In the Case if you want to store entire array into database then with serialze() it would be useful to store an entire array in a field in a database.
You can pass an array to the function, and it will return a string that is essentially the string. 
You can then unserialize() it to obtain the full array once again.


example:


<?php

$str_array = array( "Rajesh Sharma", "Rajesh", "RajeshS" );
$serialized_str = serialize($str_array);
echo $serialized_str;


?>


This will output a:3:{i:0;s:14:"Rajesh Sharma";i:1;s:6:"Rajesh";i:2;s:7:"RajeshS";}
so you can store entire array in a field in a database.


<?php

$str_array = array( "Rajesh Sharma", "Rajesh", "RajeshS" );
$serialized_str = serialize($str_array);


print_r(unserialize($serialized_str));


?>
This will output a Array ( [0] => Rajesh Sharma[1] => Rajesh [2] => RajeshS ).


Bookmark and Share

What is access modifier?

Access modifier:
OOP provides data-hiding capabilities with public, protected, and private data attributes and methods:


Public : A public variable or method can be accessed directly by any user of the class.


Protected : A protected variable or method cannot be accessed by users of the class but can be accessed inside a subclass that inherits from the class.


Private:A private variable or method can only be accessed internally from the class in which it is defined.


Bookmark and Share

Constructor and Desctructor.

Constructor:


PHP 5 allows developers to declare constructor methods for classes.Classes call constructor method on each newly-created object. 
function __construct() {
//
}
Example:


<?php
class MainClass {
   function __construct() {
      echo "In MainClass constructor\n";
   }
}


class ChildClass extends MainClass {
   function __construct() {
       parent::__construct();
      echo "In SubClass constructor\n";
   }
}


$obj = new MainClass();
$obj = new SubClass();
?>
Note: If  PHP 5 cannot find a __construct() function for a given class, it will search for the old constructor function, by the name of the class. 


Destructor:


The destructor method will be called as soon as Classes destroy the object.


 function __destruct() {
  //     
   }
Example:


<?php
class MainClass {
   function __construct() {
      echo "In MainClass constructor\n";
   }
function __destruct() {
       print "Destroying \n";
   }
}
class ChildClass extends MainClass {
   function __construct() {
       parent::__construct();
      echo "In SubClass constructor\n";
   }
   
}


$obj = new MainClass();
$obj = new SubClass();
?>


Note:The destructor method will be called even if script execution is stopped using exit().


Bookmark and Share

Static Methods and Properties


Static Methods and Properties:


In this Article,I will explain how to use  Static properties or methods in PHP5.

  • To implement static keyword functionality to the attributes or the methods will have to be prefix with static keyword.
  • Static properties or methods can be accessible without needing an instantiation of the class.
  • A property declared as static can not be accessed with an instantiated class object.
  • $this is not available inside the method declared as static.
  • Static properties cannot be accessed using the arrow operator ->. 
  • Static properties can be accessed using the Scope Resolution Operator (::) operator.

                                                  ClassName::$staticvar= $value;


Example:

<?php 
class Box
{
   static private $color;  
   function __construct($value)
   {
  if($value != "")
  {
   Box::$color = $value; 
  }
  $this->getColor();
   }
   public function getColor()
   {
  echo Box::$color ;
   }
    
   static public function StaticMethod() {


        echo self::$color;


    }


}
$a = new Box("RED");
Box::StaticMethod();
$a = new Box("GREEN");
$a = new Box("");
?>


OUTPUT:
RED
RED 
GREEN
GREEN


Bookmark and Share

Static Keyword

Static Keyword:


In this Article,I will explain how to use Static Keyword in PHP5.
  • To implement static keyword functionality to the attributes or the methods will have to be prefix with static keyword.
  • Static properties or methods can be accessible without needing an instantiation of the class.
  • A property declared as static can not be accessed with an instantiated class object.
  • $this is not available inside the method declared as static.
  • Static properties cannot be accessed using the arrow operator ->. 
  • Static properties can be accessed using the Scope Resolution Operator (::) operator.
                                                  ClassName::$staticvar= $value;

Example:


<?php
class Box
{
   static private $color;  

   function __construct($value)
   {
if($value != "")
{
Box::$color = $value; 
}
$this->getColor();
   }

   public function  getColor ()
   {
echo Box::$color;
   }
}

$a = new Box("RED");
$a = new Box("GREEN");
$a = new Box("");
?>

OUTPUT:
RED
GREEN
GREEN


Bookmark and Share

Difference between abstract classes and interfaces?

Abstract Class:
  • To define a class as Abstract, the keyword abstract is to be used. 
  • In abstract class at least one method must be abstract.
  • we can create object of abstract class.
  • abstract classes may not be instantiated.
  • The child classes which inherits the property of abstract base class, must define all the methods declared as abstract.
  • Any class that contains at least one abstract method must also be abstract.
  • If the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.
  • Abstract class can contain variables and concrete methods.
  • A class can Inherit only one Abstract class and Multiple inheritance is not possible for Abstract class.

Interfaces:
  • In interface all the method must be abstract.
  • All methods declared in an interface must be public.
  • Interfaces cannot contain variables and concrete methods except constants.
  • A class can implement many interfaces and Multiple interface inheritance is possible.
  • To extend from an Interface, keyword implements is used.



Bookmark and Share

What is Abstract Class?

Abstract Class:


To define a class as Abstract, the keyword abstract is to be used e.g. abstract class ClassName { }
  • In abstract class at least one method must be abstract.
  • we can create object of abstract class.
  • Abstract classes may not be instantiated.
  • The child classes which inherits the property of abstract base class, must define all the methods declared as abstract.
  • Any class that contains at least one abstract method must also be abstract.
  • If the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.
  • Abstract class can contain variables and concrete methods.
  • A class can Inherit only one Abstract class and Multiple inheritance is not possible for Abstract class.
Example:


<?php
abstract class AbstractClass
{
    abstract protected function getValue();
    abstract protected function setValue($val);


    public function Display() {
        print $this->getValue() . "\n";
    }
}


class ChildClass1 extends AbstractClass
{
    protected function getValue() {
        return "ChildClass1";
    }


    public function setValue($val) {
        return "ChildClass{$val}";
    }
}


class ChildClass2 extends AbstractClass
{
    public function getValue() {
        return "ChildClass2";
    }


    public function setValue($val) {
        return "ChildClass{$val}";
    }
}


$class1 = new ChildClass1;
$class1->Display();
echo "<br>";
echo $class1->setValue('1') ."\n";
echo "<br>";
$class2 = new ChildClass2;
$class2->Display();
echo "<br>";
echo $class2->setValue('2') ."\n";
?>


Bookmark and Share

What is Interface?

Interfaces:
  • In interface all the method must be abstract(only define).
  • All methods declared in an interface must be public.
  • Interfaces cannot contain variables and concrete methods except constants.
  • A class can implement many interfaces and Multiple interface inheritance is possible.
  • To extend from an Interface, keyword implements is used.
Example:


interface Shape
 {
function getShape();
}

class Circle implements Shape{
public function getShape() {
return "This is Shape of the Circle\n";
}
}

class MultiInher {
public function read(Shape $s) {
$shape = $s->getShape();
//
echo $shape;
}
}

$c = new Circle();

$m = new MultiInher();
$m->read($c);


Bookmark and Share

What is Encapsulation?

Encapsulation:
The wrapping of data and function together in a single unit(class) is called encapsulation.
In PHP 4 objects were little more than arrays.In PHP 5 you get much more control by visibility, 
interfaces,and more.


PHP5 provides data-hiding capabilities with public, protected, and private data attributes and methods:


Public : A public variable or method can be accessed directly by any user of the class.


Protected : A protected variable or method cannot be accessed by users of the class but can be accessed inside a subclass that inherits from the class.


Private: private variable or method can only be accessed internally from the class in which it is defined.


E.g.:
class is a protective wrapper which binds data and methods together,they can be accessed only though object of that class.


Example:


<?php 


class Shape { 


     private static $_circle; 


     public function Circle( ) { 
          if( $this->_circle == null ) { 
               $this->_circle = new Circle(); 
          } 
          return $this->_circle; 
     } 





class Circle { 


     private $_radius; 


     public function __construct() { 
          $this->_radius = "10"; 
     } 


     public function GetRadius() { 
          return $this->_radius; 
     } 



$shape= new Shape(); 


echo $shape->Circle()->GetRadius(); 
?>


Bookmark and Share

Explain about Abstraction?

In this tutorial ,I will explain about abstract class in PHP, how to declare and use of an abstract class.

Abstract Class:
It may contain one or more abstract methods.abstract classes may not be instantiated.The child classes which inherits the property of abstract base class, must define all the methods declared as abstract.
Any class that contains at least one abstract method must also be abstract.
if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.

Example:

<?php
abstract class AbstractClass
{
    abstract protected function getValue();
    abstract protected function setValue($val);

    public function Display() {
        print $this->getValue() . "\n";
    }
}

class ChildClass1 extends AbstractClass
{
    protected function getValue() {
        return "ChildClass1";
    }

    public function setValue($val) {
        return "ChildClass{$val}";
    }
}

class ChildClass2 extends AbstractClass
{
    public function getValue() {
        return "ChildClass2";
    }

    public function setValue($val) {
        return "ChildClass{$val}";
    }
}

$class1 = new ChildClass1;
$class1->Display();
echo "<br>";
echo $class1->setValue('1') ."\n";
echo "<br>";
$class2 = new ChildClass2;
$class2->Display();
echo "<br>";
echo $class2->setValue('2') ."\n";
?>


Bookmark and Share

Dynamically Add/Remove rows in HTML table using JavaScript

This article shows you how to add/delete rows to an HTML table dynamically,using DHTML and JavaScript.Using JavaScript to add/delete rows from a table in HTML dynamically.Dynamically add or remove rows in an HTML table.Add rows and delete specific rows dynamically from an HTML table
This article shows you how to add/delete rows to an HTML table dynamically, using DHTML and JavaScript.The code has been tested to work with Firefox . It may work with other browsers.The sample code has two JavaScript functions - one to add new rows and the other to delete rows.
Example:


<HTML>
<HEAD>
    <TITLE> Add/Remove dynamic rows in HTML table </TITLE>
    <SCRIPT language="javascript">
        function addRow(table_Id) {

            var table = document.getElementById(table_Id);

            var rowCnt = table.rows.length;
            var row = table.insertRow(rowCnt);

            var RowCell1 = row.insertCell(0);
            var e = document.createElement("input");
            e.type = "checkbox";
            RowCell1.appendChild(e);

            var RowCell2 = row.insertCell(1);
            RowCell2.innerHTML = rowCnt + 1;

            var RowCell3 = row.insertCell(2);
            var e2 = document.createElement("input");
            e2.type = "text";
            RowCell3.appendChild(e2);

        }

        function deleteRow(table_Id) {
            try {
            var table = document.getElementById(table_Id);
            var rowCnt = table.rows.length;

            for(var i=0; i<rowCnt; i++) {
                var row = table.rows[i];
var selected_chkbox = row.cells[0].childNodes[0];
                if(null != selected_chkbox && true == selected_chkbox.checked) {
                    table.deleteRow(i);
                    rowCnt--;
                    i--;
               
 }
            }
            }catch(e) {
                alert(e);
            }
        }

    </SCRIPT>
</HEAD>
<BODY>
     <TABLE id="table_Id"  border="1">
        <TR>
            <TD><INPUT type="checkbox" name="chekbx"/></TD>
            <TD> 1 </TD>
            <TD> <INPUT type="text" /> </TD>
        </TR>
    </TABLE>
<INPUT type="button" value="ADD ROW" onclick="addRow('table_Id')" />
<INPUT type="button" value="DELETE ROW" onclick="deleteRow('table_Id')" />

</BODY>
</HTML>


Bookmark and Share

What are different properties provided by Object-oriented systems ?

What are different properties provided by Object-oriented systems ?Can you explain different properties of Object Oriented Systems? Whats difference between Association , Aggregation and Inheritance relationships?
Properties of Object Oriented Systems:
  • support inheritance
  • provides encapsulation of data
  • provides extensibility of existing data types and classes
  • provide support for complex data types
  • Inheritance-one class inherite the property of another class..
  • Aggregation-.is a part whole relationship.
  • Association.:is a relationship between 1 or more instances of a class.





Bookmark and Share

What is the relation between Classes and Objects

What is the relation between Classes and Objects.Class is a definition, while object is a instance of the class created
What is the relation between Classes and Objects

Class is a definition, while object is a instance of the class created. 
class is like a blueprint/template in OOPs, and this template is used to create objects.The collection of properties & behavior of an object is also called as class.
A class contains  properties, fields, data members, attributes.


Example:

Car is an object , cars is a class
            public class cars
            {
                  //
            }


According to the sample given below we can say that the cars object, named object_car, has created out of the cars class.

               cars object_car = new cars();

object is an instance of a class.An object is an entity that has attributes, behavior, and identity. Objects are members of a class.
Objects are accessed, created or deleted during program run-time.

Declaration of an Object in OOPs
ClassName objectName=new ClassName();
Example:
          Car objCar= new Car();



Attribute in OOPs: Attributes define the characteristics of a class. In Class Program attribute can be a string or it can be a integer. 
Behavior in OOPS:  Every object has behavior.
Identity in OOPS:  Each time an object is created the object identity is been defined.



Bookmark and Share