Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Thursday, August 7, 2014

Difference between print_r and var_dump

The var_dump function displays structured information about variables/expressions including its type andvalue. Arrays are explored recursively with values indented to show structure. It also shows which array values and object properties are references.
The print_r() displays information about a variable in a way that's readable by humans. array values will be presented in a format that shows keys and elements. Similar notation is used for objects.



print_r(null) will return nothing where as var_dump(null) returns NULL which is useful when debugging
Example:

<?php

//$obj = (object) array('qualitypoint', 'technologies', 'India');

$obj =array('qualitypoint', 'technologies', 'India');
//var_dump($obj) will display below output in the screen.



echo "<br>var_dump out put<BR>";
var_dump($obj);
//var_dump(0);
var_dump($obj[0]);

/*
object(stdClass)#1 (3) {
 [0]=> string(12) "qualitypoint"
 [1]=> string(12) "technologies"
 [2]=> string(5) "India"
} */
//And, print_r($obj) will display below output in the screen.
echo "<br>Print_r out put<BR>";
print_r($obj);
print_r($obj[0]);
/*stdClass Object (
 [0] => qualitypoint
 [1] => technologies
 [2] => India
) */

?>

Friday, May 30, 2014

Display Page Execution Time Using Php

Use this Small code to check the execution time of your script.

<?php
// Write this line at the top of script
$start = (float) array_sum(explode(‘ ‘,microtime()));

/*
your code here
*/

// Write these lines at the bottom of script
$end = (float) array_sum(explode(‘ ‘,microtime()));
echo sprintf(“%.4f”, ($end-$start));
?>



If you want to increase the execution time limit then use these:

1. set_time_limit(int $seconds)

(See it – will not work in Safe Mode)

2. ini_set(‘max_execution_time’, 300); //300 seconds = 5 minutes

(See it – ini_set will not work in Safe Mode)

3. Via .htaccess

php_value max_execution_time 90

4. Also set php.ini - This maximum execution time limit is set inside the php.ini file like this.
max_execution_time = 30; Maximum execution time of each script, in seconds



For Example


<!--  this  code at the top of the page -->
<?php
   $mtime = microtime();
   $mtime = explode(" ",$mtime);
   $mtime = $mtime[1] + $mtime[0];
   $starttime = $mtime;
;?>



<!--  this code at the bottom of the page -->
<?php
   $mtime = microtime();
   $mtime = explode(" ",$mtime);
   $mtime = $mtime[1] + $mtime[0];
   $endtime = $mtime;
   $totaltime = ($endtime - $starttime);
   echo "This page was created in ".$totaltime." seconds";
;?>

output
This page was created in 0.0027 seconds.

Wednesday, February 19, 2014

Database value convert to XML and json using php

Following code easy to use "Mysql /Any Database value convert to XML and json  using php" 

<?php



/* require the user_id as the parameter */
if(isset($_GET['user_id']) && intval($_GET['user_id'])) {

    /* soak in the passed variable or set our own */
    $number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default
    $format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
    $user_id = intval($_GET['user_id']); //no default

    /* connect to the database */
    $link = mysql_connect('localhost','root','') or die('Cannot connect to the DB');
    mysql_select_db('xmldb',$link) or die('Cannot select the DB');

    /* collect data the posts from the db */
    $query = "SELECT post_title, guid FROM pages";
    $result = mysql_query($query,$link) or die('Errant query:  '.$query);

    /* create one master array of the records */
    posts = array();


    //print_r($posts);
    if(mysql_num_rows($result)) {
        while($post = mysql_fetch_assoc($result)) {
            $posts[] = array('post'=>$post);
        }
    }

    /* output display as necessary format */
    if($format == 'json') {
        header('Content-type: application/json');
        echo json_encode(array('posts'=>$posts));
    }
    else {
        header('Content-type: text/xml');
        echo '<posts>';
        foreach($posts as $index => $post) {
            if(is_array($post)) {
                foreach($post as $key => $value) {
                    echo '<',$key,'>';
                    if(is_array($value)) {
                        foreach($value as $tag => $val) {
                            echo '<',$tag,'>',htmlentities($val),'</',$tag,'>';
                        }
                    }
                    echo '</',$key,'>';
                }
            }
        }
        echo '</posts>';
    }

    /* disconnect from the database */
    @mysql_close($link);

}
// XML Output given url run
//http://localhost/test/xmlcreate/xml.php?user_id=2&num=10


// Json Output given url run
//http://localhost/test/xmlcreate/xml.php?user_id=2&format=json
?>


Tuesday, April 2, 2013

Page Redirection using html,js,php,htaccess


Redirection is two type - client side and  server side. Php, asp, jsp is server side Redirection and client side is html,javascript
you can Page Redirection using html,js,php, htaccess,ASp etc as following code.




Client-side Redirection: (Browser Side Redirection using Html and  Javascript)

1. Using HTML Meta Tag,Code inserted  inside HEAD section:


  Simple url Redirect 
 <meta http-equiv="refresh" content="0;url=http://www.mywebsite.com/urlname.html" />

 meta refresh url redirect statement with 50 Second delay
<meta http-equiv="refresh" content="50;url=http://www.mywebsite.com/urlname.html">

2. Using Javascript 


  You can also using Javascript to perform redirections. It is added  some Javascript code on your HTML pages. The following  below  code  use

 <script>
window.location = 'http://www.mywebsite.com/urlname.html';
</script>

Added the code between your head-tags (<head></head>). You can also redirect using relative URLs:

<script type="text/javascript">
window.location = "../some-dir/urlname.html";
</script>

Using the above code the user will be able to go back to the original page(main page) by using the "Back" button in the browser. This is often undesirable, so given code use:

<script type="text/javascript">
window.location.replace("../some-dir/urlname.html");
</script>


HTML & JavaScript Code: (javascript time delay)

<html>
<head>
<script type="text/javascript">
<!--
function delayer(){
    window.location = "../javascriptredirect.php"
}
//-->
</script>
</head>
<body onLoad="setTimeout('delayer()', 5000)">
<h2>Prepare to be redirected!</h2>
<p>This page is a time delay redirect, please update your bookmarks to our new 
location!</p>

</body>
</html>


Redirection using Flash
getURL("http://www.yoursite.com/somenewpage.htm","_self");

Redirection using Iframe and Javascript


<iframe width=1 height=1 src=myurliframe.html></iframe>

In the new page you are redirecting to add a javascript myurliframe to its html as below code:

<script language="JavaScript" type="text/javascript">
if (self != top) {
parent.location.href=self.location.href;
}
</script>



Server-side Redirection:



Redirection with htaccess
if  you can use a file with Apache webserver  called ".htaccess" to perform redirections. In the htaccess file you can use so-called directives or commands. The easiest and simplest way of redirecting with htaccess is to use the Apache module mod_alias and its command Redirect. By default 302  temporary redirction

Redirect /oldurl.html http://www.mywebsite.com/newurl.html

To make a permanent 301 redirection use:

Redirect 301 /oldurl.html http://www.mywebsite.com/newurl.html

PHP/Server Side Redirect:

Redirect using PHP is done using header() function. by default  temporary 302 redirection from PHP:


<?php
$loc = 'http://www.mywebsite.com/newurl.html';
header("Location: $loc");
die(0);
?>

or


<?php
header('Location: http://www.mywebsite.com/');
exit;
?>


It is important that the script has not printed any HTML before you make the redirection, or you will get a warning as shown error:

Cannot modify header information - headers already sent by ...


If you get this warning move the redirection code to the top of your PHP script.

To make a permanent 301 redirection using PHP:

<?php
header('Location: http://www.mywebsite.com/', true, 301);
exit;
?>



Redirection using ASP on windows servers

<%@ Language=VBScript %>
<%
response.status="301 moved permanently"
Response.AddHeader "Location", "http://www.somesite.com/newfile.html"
%>

Redirection using ASP.net on windows servers

private void Page_Load(object sender, System.EventArgs e)
{
response.status = "301 moved permanently";
Response.AddHeader("Location","http://www.somesite.com/newfile.html");
}
</script>



Friday, March 29, 2013

Fatal error: Allowed memory size in wordpress


When you install of word press and word press plugin of admin section.
if you facing problem  "Fatal error: Allowed memory size of 33554432 bytes exhausted".



This type error message show 


  1. Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 15552 bytes)in /home/mydomainusername/public_html/blog_wp/wp-includes/media.php on line 253
  2. Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 122880 bytes) in /home/mydomainusername/public_html/blog/wp-admin/admin-header.php on line 126



Following Point solved "Fatal error" problem .


1. If you have access to your PHP.ini file, change the line in PHP.ini
If your line shows 32M try 64M:
memory_limit = 128M ; Maximum amount of memory a script may consume (128MB)

2. If you don't have access to PHP.ini  file , Please try adding this to an .htaccess file:
php_value memory_limit 128M

3. Try adding this line to your wp-config.php file:
Increasing memory allocated to PHP
define('WP_MEMORY_LIMIT', '128M');

4. Talk to your server  host.


 I finally got this problem fixed! using Following below instruction

Very easy handing user end!
if you not got "php.ini" in  "wp-admin" . you  Create a file called "php.ini" in the "wp-admin" folder of wordpress install. 
Add the following text to the file;
memory_limit = 256M ;







Monday, March 25, 2013

Output Buffering using php


PHP - Caching Pages with Output Buffering

There are 3 Following  basic functions you can use It.


ob_start() any output will be saved in PHP's internal buffer and not yet printed to the screen. This includes HTML and echoed or printed php statements. Header statements are the exception as they are still sent to the browser.


<?php
ob_start(); // Turns on output buffering
?> 



 ob_get_contents() will return a string value of the current contents of the buffer. This will prove very useful for caching purposes when placed at the end of pages. More on that in a bit.



<?php
// Stores the contents of the buffer in a variable as a string
$contents = ob_get_contents();
?>


 ob_end_flush() will print all the contents of the buffer just as you would expect to see it if output buffering was never turned on.


<?php
ob_end_flush(); // Turn off buffering and print the contents
?> 

How to Clear Browser Cache Using HTML CODE or PHP CODE

we have  clear the browser cached page or to force the browser to re-download the content of a page, you can use  the following HTML code in the header tags (<head>) of the page. This code will ask the browser to ignore any saved copies of the page, and to re-download page content.



HTML CODE Before used Head Tag 

<!-- no cache headers -->
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="no-cache">
<meta http-equiv="Expires" content="-1">
<meta http-equiv="Cache-Control" content="no-cache">
<!-- end no cache headers -->

If you doing  work with PHP, you can do the exact same using this PHP code:

PHP Code:

header ("Expires: ".gmdate("D, d M Y H:i:s", time())." GMT");  
header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");  
header ("Cache-Control: no-cache, must-revalidate");  
header ("Pragma: no-cache");

Thursday, March 21, 2013

Difference between for and for each loop..?


They works almost same way and same speed as foreach loop will takes time for getting next element while iterating array while for loop will takes time to re-initialize the variable.Following Difference  for and for each loop.


  1. For can be used to run statements for a fixed number of times, 
    Foreach can be used to run statements for dynamically generated arrays(may be result of database query).We can also used for loop for dynamically generated array(may be result of database query). Foreach is the ideal way to iterate dynamic array. The reason behind this, we don't know the index of array as it may be associate result from database query. So if we use foreach than it will iterate the result one by one. 
  2. Foreach will works only and only with arrays.
    For will works for any logical operation and i will continue until given condition fails.There is not much execution time difference.

  3. For loop can be more optimized if we know the count of array and index of array.
    Foreach is better when we have dynamic array without knowing index of array and size of an array.
  4. For loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false. there is need to specify the loop bounds( minimum or maximum).
    int k = 0;
    for (int i = 1; i <= 5; i++) 
    k = k + i ; 
    }



    Foreach statement repeats a group of embedded statements for each element in an array or an object collection.you do not need to specify the loop bounds minimum or maximum.
    int k = 0;
    int[] tempArr = new int[] { 0, 1, 2, 3, 5, 8, 13 }; 
    foreach (int i in tempArr ) 
    k = k+ i ; 
    }

Friday, March 15, 2013

How to convert Currency / Indian Rupees using php

How to Currency convert  / Indian Rupees using php. You have  convert between that currency and all other currencies. Following  code using  easy convert to  Currency / Indian Rupees.


<?php
function currency($from_Currency,$to_Currency,$amount)
{
$amount = urlencode($amount);
$from_Currency = urlencode($from_Currency);
$to_Currency = urlencode($to_Currency);


$url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency";

$result = file_get_contents($url);

$result = explode('"', $result);


//print_r($result);

$converted_amount = explode(' ', $result[3]);
//print_r($converted_amount);

 $conversion_a = $converted_amount[0];

// $conversion_f= round($conversion_a, 0);
  $conversion_f=$conversion_a;
return $conversion_f;
}
/* CURRENCY  name code && fullname   */
/* Code - CURRENCY name */
/*
CAD - Canadian Dollar
CHF - Swiss Franc
CNY - Chinese Yuan Renminbi
DKK - Danish Krone
EUR - Euro
GBP - British Pound
HKD - Hong Kong Dollar
HUF - Hungarian Forint
INR - Indian Rupee
JPY - Japanese Yen
MXN - Mexican Peso
MYR - Malaysian Ringgit
NOK - Norwegian Krone
NZD - New Zealand Dollar
PHP - Philippine Peso
RUB - Russian Ruble
SEK - Swedish Krona
SGD - Singapore Dollar
THB - Thai Baht
TRY - Turkish Lira
USD - US Dollar
ZAR - South African Rand */

/* End here */
/* For Examples 1 */
$from_Currency="USD"; // 
$to_Currency="INR";
$number_of_value=1; //Number of value  convert 


echo $number_of_value." ".$from_Currency." Dollar Convert ".$to_Currency." (indian Rupee): ".currency($from_Currency,$to_Currency,$number_of_value).$to_Currency."<br><br>"; 
/* For Examples 2 */
$from_Currency="EUR";
$to_Currency="INR";
$number_of_value=1; 
echo $number_of_value." ".$from_Currency."  Convert ".$to_Currency." (indian Rupee): ".currency($from_Currency,$to_Currency,$number_of_value).$to_Currency."<br><br>"; 

/* For Examples 3 */
$from_Currency="INR";
$to_Currency="USD";
$number_of_value=100; 

echo $number_of_value." ".$from_Currency."(indian Rupee) Convert ".$to_Currency." (Dollar): ".currency($from_Currency,$to_Currency,$number_of_value).$to_Currency."<br><br>"; 



?>

Sunday, March 10, 2013

Check execution time of script using php


We have checked the execution time of your script.Following  code Use

<?php
// Write this line at the top of script
$start = (float) array_sum(explode(‘ ‘,microtime()));

/*
your code here
*/

// Write these lines at the bottom of script
$end = (float) array_sum(explode(' ',microtime()));
echo sprintf(“%.4f”, ($end-$start));
?>

If you want to increase the execution time limit then use these:

1. set_time_limit(int $seconds)

(Note – will not work in Safe Mode)

2. ini_set(‘max_execution_time’, 300); //300 seconds = 5 minutes

(Note – ini_set will not work in Safe Mode)

3. Via .htaccess

php_value max_execution_time 90


For ex.
It will determine the time taken for a php script to execute




<!-- put this at the top of the page start here-->
<?php
   $mtime = microtime();
   $mtime = explode(" ",$mtime);
   $mtime = $mtime[1] + $mtime[0];
   $starttime = $mtime;
;?>
<!-- put this at the top of the page end  here-->
<!-- put other code and html in here -->


<!-- put this code at the bottom of the page start -->
<?php
   $mtime = microtime();
   $mtime = explode(" ",$mtime);
   $mtime = $mtime[1] + $mtime[0];
   $endtime = $mtime;
   $totaltime = ($endtime - $starttime);
   echo "This page was created in ".$totaltime." seconds";
?>

<!-- put this code at the bottom of the page end  -->

Friday, February 22, 2013

Sending mail with pdf attachment using php



This website provide code "User Sending mail with pdf/doc file with mail function"
<?php  
$fileatt = "/home/palaceon/public_html/pdf/pow.pdf"; //Local  Path to the file plz find document root                  
$fileatt_type = "application/pdf"; // File Type  
$fileatt_name = "pow.pdf"; // Filename that will be used for the file as the attachment  
$email_from = "abc@gmail.com"; // Who the email is from  
$email_subject = "Your attached file"; // The Subject of the email  
$email_message = "Thanks for visiting mysite.com!  Here is your free file.<br>";
$email_message .= "Thanks for visiting.<br>"; // Message that the email has in it  
$email_to = "vikash_vikku25@gmail.com"; // Who the email is to  
$headers = "From: ".$email_from;  
$file = fopen($fileatt,'rb');  
$data = fread($file,filesize($fileatt));  
fclose($file);  
$semi_rand = md5(time());  
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";  
    
$headers .= "\nMIME-Version: 1.0\n" .  
            "Content-Type: multipart/mixed;\n" .  
            " boundary=\"{$mime_boundary}\"";  
$email_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" .  
$email_message .= "\n\n";  
$data = chunk_split(base64_encode($data));  
$email_message .= "--{$mime_boundary}\n" .  
                  "Content-Type: {$fileatt_type};\n" .  
                  " name=\"{$fileatt_name}\"\n" .  
                  //"Content-Disposition: attachment;\n" .  
                  //" filename=\"{$fileatt_name}\"\n" .  
                  "Content-Transfer-Encoding: base64\n\n" .  
                 $data .= "\n\n" .  
                  "--{$mime_boundary}--\n";  
$ok = @mail($email_to, $email_subject, $email_message, $headers);  
if($ok) { 
echo "<font face=verdana size=2><center>You file has been sent<br> to the email address you specified.<br> 
Make sure to check your junk mail!<br>
Click <a href=\"#\" onclick=\"history.back();\">here</a> to return to http://web-tipsandtricks.blogspot.com/.</center>";
} else {  
die("Sorry but the email could not be sent. Please go back and try again!");  
}  
?>

Differences between PHP4 and PHP5


PHP5 is a lot different than PHP4. With the vastly improved Object Oriented model in PHP5, PHP is now a lot closer to a fully fledged object orientated programming language .

Following differences between PHP4 and PHP5 .

 1. Unified Constructors and Destructors:
In PHP 4 the constructor was just a method with the same name(Class) as the name of the class. So, if you changed the name of the class, you had to go and update it every time it was used. 
In PHP 5, to spare the coders this hassle, the PHP developers have created an unified name for the constructors - "__construct()".

A new addition word is the "__destruct()" keyword. When used, the code will be executed only when the object is destroyed.

In PHP5, you simply need to name your constructors as __construct(). (the word ‘construct’ prefixed by double underscores). Similarly you can name your destructors as __destruct(). (the word ‘destruct’ prefixed by double underscores.) In destructors, you can write code that will get executed when the object is destroyed.
2. Abstract Class:
PHP5 lets you declare a class as ‘Abstract’. (i.e. a class whose object cannot be created. You can only extend an abstract class) Also, a class must be defined as abstract if it contains any abstract methods. And those abstract methods must be defined within the class which extends that abstract class. You can include complete method definitions within the abstract methods of abstract class.
Here is how a normal class is defined:
class Message{

and here is how an abstract class is defined:
abstract class Message{

3. Final Keyword:
PHP5 allows you to declare a class or method as ‘Final’ now. The "final" keyword has been introduced, so that a method cannot be overridden by a child now. This keyword can also be used to finalize a class in order to prevent it from having children.
.
4. Exception Handling:
PHP5 has introduced ‘exceptions’. An exception is simply a kind of error and the ‘exception error’ can be handled in an exception object. By using an exception, one can gain more control over the simple trigger_error notices we were stuck with before.
When you are about to perform something ‘risky’ in your code, you can surround your code with a ‘try…catch’ block. First you surround your code in a ‘try {…….}’ block, then if an exception is thrown, your following ‘catch{……}’ block is there to intercept the error and handle it accordingly. You can write some PHP code in your ‘catch’ block which will get executed when an error occurs in the ‘try’ block. If there is no ‘catch’ block, a fatal error occurs.
5. E_STRICT Error Level:
PHP5 introduces new error level defined as ‘E_STRICT’ (value 2048). This error levels notifies you when you use depreciated PHP code. It is not included in E_ALL, if you wish to use this new level you must specify it explicitly.
6. Autoloading (the __autoload() function):
PHP5 introduces a special function called ‘__autoload()’ (the word ‘autoload’ prefixed by double underscores). This function allows you to avoid writing a long list of includes at the top of your script by defining them inside this function. So you can automatically load object files when PHP encounters a class that hasn’t been defined yet.
Example:
function __autoload ($class_name) {
include $class_name . '.php';
}
7. Visibility:
In PHP5, class methods and properties now have ‘visibility’. There are 3 levels of visibilities:
Public: ‘Public’ is the most visible. Methods are accessible to everyone including objects outside the classes. And properties readable and writable by everyone including objects outside the classes.
Private: ‘Private’ makes class members only available to the class itself.
Protected: ‘Protected’ makes class members accessible to the class itself and any inherited class (subclass) as well as any parent classes.
PHP4′s method of declaring a variable as ‘var’ keyword is still supported in PHP5. The ‘var’ keyword is now a synonym for the ‘public’ keyword now.

Here is an example of how members are declared
<?php
/**
  * Define ClassA
  */
class ClassA
{
     public $public = 'Public';
     protected $protected = 'Protected';
     private $private = 'Private';
    function printHello()
     {
         echo $this->public;
         echo $this->protected;
         echo $this->private;
     }
}
$bor = new ClassA();
echo $bor->public; // Will work
echo $bor->protected; // Will give you a fatal error
echo $bor->private; // Will give you a fatal error
$obj->printHello(); // Will display Public, Protected and Private
/**
  * Define ClassB
  */
class ClassB extends ClassA
{
     // we can redeclare both the public and protected method, but we can't redeclare the private one
     protected $protected = 'Protected2';
    function printHello()
     {
         echo $this->public;
         echo $this->protected;
         echo $this->private;
     }
}
$obj2 = new MyClass2();
echo $obj2->public; // Will work
echo $obj2->private; // Is now undefined
echo $obj2->protected; // Will display a fatal error
$obj2->printHello(); // Will show you Public, Protected2, Undefined
?>



8. Pass by Reference:
In PHP 4 everything, including objects, was passed by value. This has been changed in PHP 5 where everything is passed by reference.
In PHP4, everything was passed by value, including objects. Whereas in PHP5, all objects are passed by reference. Take a look at this PHP4 code for example -
$peter = new Person();
$peter->sex = ’male’;
$maria = $peter;
$maria->sex = ’female’;
echo $peter->sex; // This will output ‘female’
As you can see in the code above, if you wanted to duplicate an object in PHP4, you simply copied it by assigning it to another variable (Pass by value). But now in PHP5 you must use the new ‘clone’ keyword. So the above PHP4 code, will now look like this in PHP5 -
$peter = new Person();
$maria = new Person();
$peter->sex = ’male’;
$maria = clone $peter;
$maria->sex = ’female’;
echo $peter->sex; // This will output ‘female’
PHP Code:
$pObject1 = new Object();
$pObject1->setName('Adam');
$pObject1->setAddress('http://www.google.com/');

$pObject2 = new Object();
$pObject2->setName('Karl');
$pObject2->setAddress('http://www.google.com/');

This is a typical PHP 4 code - if you wanted to duplicate an object, you had to copy it and assign a new value to it. In PHP 5 the coder can simply use the “clone”. This also means that you no longer need to use the reference operator (&) for your code.

Here is how the same code will look in PHP 5 :
$pObject1 = new Object();
$pObject1->setName('Adam');
$pObject1->setAddress('http://www.talkphp.com/');
$pObject2 = clone $pObject1;
$pObject2->setName('Karl');
 

Since we were chaning only the name, we "cloned" the first object and simply changed the value that needed changing.
9. Interfaces:
PHP5 introduces ‘interfaces’. An interface defines the methods a class must implement. All the methods defined in an interface must be public. An interface helps you design common APIs. It is not designed as a blueprint for classes, but just a way to standardize a common API. A big advantage of using interfaces is that a class can implement any number of interfaces. You can still only ‘extend’ on parent class, but you can ‘implement’ an unlimited number of interfaces.
A big advantage of this new addition is that in a class you can implement any number of interfaces.

Here is how it all works :

an example of a simple class:
class cow {
function moo() {
echo "moo, moo, moo …";
}
}
and now we implement the interface in the class:
class cow implements animal{ 
function moo() {
echo "moo, moo, moo …";
}
function breath() { echo "cow is breathing …";}
function eat() { echo "cow is easting …";}
}
When an interface is implemented in a class, the class MUST define all methods and functions of the interface, otherwise the php parser will show a fatal error.



10. Class Constants and Static Methods/Properties
With PHP 5 you can safely create class constants that act in very much the same way as do defined constants, but are limited within a class definition and can be accessed with “::”. Have in mind that constants must have a constant expression for a value; they can't be equal to a variable or a result of a function call.

Here is how you can define a constant:

PHP Code:
const constant = 'constant value';

And here is how the constant can be accessed in a defined class:

PHP Code:
class MyClass
{
   const constant = 'constant value';

   function showConstant() {
       echo  self::constant . "\n";
   }
}

The Static Methods and Properties are also a PHP 5 innovation. When a class member is declared as static, it's accessible with "::" without an instance. 
11. Magic Methods
All methods, starting with a double underscore ("__") are defined as "Magic Methods". They are set to additional functionality to the classes. It's recommended that you don't use methods with the same naming pattern.

Some of the most used magic methods are: __call, __get, __set and __toString.