Wednesday, September 22, 2010

Creating a file based logging script

In this tutorial I will show you how you can create a small and simple PHP script to log your visitors activity into a file. You just need to add 1 line to each of your page to enable logging and the statistics will be collected in a html file so you don't have to setup any database for this task.

Step 1.
A basic logging script need to log visitors information in an easy and well-arranged format. In general the site owner want to know which pages of his/her site were visited most often, what source was the referrer and so on.

In this tutorial we will collect the following information about the visitor:
  • Visiting date
  • Visitor IP
  • Visitor hostname
  • Visitor browser type
  • The visited page
  • The referrer to the page

From this information you can the site owner can make any decision how to improve the site.


Step 2.
Now it's time to make some coding as well. To get the visitors IP, browser, referrer and visited page we can use the PHP built in super global variable the $_SERVER. From this array we can read out the above mentioned properties and their values.

So the code is the following:

php
    $userAgent 
= ( isset($_SERVER['HTTP_USER_AGENT'])
                     && (
$_SERVER['HTTP_USER_AGENT'] != ""))
                 ? 
$_SERVER['HTTP_USER_AGENT'] : "Unknown";
                
    
$userIp    = ( isset($_SERVER['REMOTE_ADDR'])
                      && (
$_SERVER['REMOTE_ADDR'] != ""))    
                  ? 
$_SERVER['REMOTE_ADDR']     : "Unknown";
                 
    
$refferer  = ( isset($_SERVER['HTTP_REFERER'])
                     && (
$_SERVER['HTTP_REFERER'] != ""))
                 ? 
$_SERVER['HTTP_REFERER']    : "Unknown";
                
    
$uri       = ( isset($_SERVER['REQUEST_URI'])
                      && (
$_SERVER['REQUEST_URI'] != ""))
                  ? 
$_SERVER['REQUEST_URI']     : "Unknown";
?>

Explanation:
The $_SERVER array key definition are the following:

HTTP_USER_AGENT : Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586).

REMOTE_ADDR: The IP address from which the user is viewing the current page.

HTTP_REFERER:
The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

REQUEST_URI: The URI which was given in order to access this page; for instance, '/index.html'.

So we try to read this information if the actual properties doesn't exists or empty than we set it to 'Unknown'.

To get the hostname from the userIp I use the PHP built in function gethostbyaddr() which gets the Internet host name corresponding to a given IP address. Besides this getting the actual date is quite easy by using the date() function with a predefined date format string.

This part of the code looks like this:

php
    define
("DATE_FORMAT","d-m-Y H:i:s");

    
$hostName   gethostbyaddr($userIp);
    
$actualTime date(DATE_FORMAT);?>

Step 3.
Now as we have the all of the visitors information so we need to store it in a file. To make it easier to read the file I will surround the data with a HTML table elements. As result when you open the log file you will get all of the information in a nice formatted HTML table.

The code which composes a log entry looks like this:

php
    $logEntry 
"
        $actualTime
        $userIp
        $hostName
        $userAgent
        $uri
        $refferer
    \n"
;?>

Now we have to make some file handling. First of all we need to check whether the log file exists or not. If the file not exists yet than we will create a new one and write some HTML header information at the beginning. If the file already exists than we open it to append a new log entry.
After it we can write the log entry to the file and close it afterwards. That's all. As the file is a html file you can easy open/display it.

The complete logger coode looks like this:

php
    define
("DATE_FORMAT","d-m-Y H:i:s");
    
define("LOG_FILE","visitors.html");

    
$logfileHeader='

    
$userAgent = ( isset($_SERVER['HTTP_USER_AGENT'])
                     && (
$_SERVER['HTTP_USER_AGENT'] != ""))
                 ? 
$_SERVER['HTTP_USER_AGENT'] : "Unknown";
                
    
$userIp    = ( isset($_SERVER['REMOTE_ADDR'])
                      && (
$_SERVER['REMOTE_ADDR'] != ""))    
                  ? 
$_SERVER['REMOTE_ADDR']     : "Unknown";
                 
    
$refferer  = ( isset($_SERVER['HTTP_REFERER'])
                     && (
$_SERVER['HTTP_REFERER'] != ""))
                 ? 
$_SERVER['HTTP_REFERER']    : "Unknown";
                
    
$uri       = ( isset($_SERVER['REQUEST_URI'])
                      && (
$_SERVER['REQUEST_URI'] != ""))
                  ? 
$_SERVER['REQUEST_URI']     : "Unknown";

    
$hostName   gethostbyaddr($userIp);
    
$actualTime date(DATE_FORMAT);

    
$logEntry "$actualTime$userIp$hostName$userAgent$uri$refferer\n";

    if (!
file_exists(LOG_FILE)) {
        
$logFile fopen(LOG_FILE,"w");
        
fwrite($logFile$logfileHeader);
    }
    else {
        
$logFile fopen(LOG_FILE,"a");
    }

    
fwrite($logFile,$logEntry);
    
fclose($logFile);?>

Step 4.
Using the logger script is quite easy. Each of your page you want to log you need to add a new line: require_once("logger.php");
If the page is not a Php page than you need to rename it from html to Php or tell the Php to interpret the *.html pages as well.

So an example file looks like this:

php
    
require_once("logger.php");

    echo 
"

This is an example page to show you how to use logger.

"
;
    echo 
"Just insert the following code into your files:
"
;
    echo 
'require_once("logger.php");';?>

Monday, September 13, 2010

Introduction To Xajax

Abstract

The Xajax class has come far in its progress and now the API has stabilized it is ready for work. This tutorial brings the absolute basics to get started with Xajax.

Hello World

Like all things, starting at the beginning is best. This script provides the absolute basics to getting Xajax working. The process is quite simply when broken down into smaller chunks. Like any PHP library, the class definition needs to be included. With xajax it is the xajax.inc.php bootstrap file that loads up the xajax environment and makes ready the ajax processes internally.
Xajax generates javascript code and provides a bridge, or callback, to PHP functions. To let Xajax know which functions are to be called, they must first be registered. The simple API of Xajax provides a register() function for this task. In the example below, the showText PHP function is registered.
When the register function is called, the returned object can be used to set parameters. In this example, the object is assigned to a variable named $rqstButton which is used later in the HTML to gene rate the onclick event code.
With the function registered, the requested function can be processed. This means the javascript for required to make a callback to PHP is generated internally and is ready to be retrieved with either the printJavascript() or getJavascript() methods.
The printJavascript() method, as the name suggests, just prints the javascript. However, a little more separation is nice, so the generated javascript can be assigned to a variable with the getJavascript() method. In these examples, the getJavascript() method is used to provide an level of separation between the HTML display code, and the PHP logic.

In the HTML, a simple echo statement is used to display the javascript generated by xajax. A little further down a call is made with javascript onClick event. The value for the onClick event is held in the rqstButton object and is simply echoed and that is really about all the javascript knowledge needed to get started, Xajax will do the rest.
But what of the showText() function itself? This function now becomes the engine room for the process. The content is contain in this function, however, in larger applications, the data may be sourced from external resources such as a database or file. A new response object is created, which will contain the information needed by xajax to perform the required actions. Again, the simple API provides a method to assign the content contained in the $content variable, to the innerHTML property of the target div named "my_div". The object response is returned and the task is complete.

    /*** include the xajax bootstrap ***/
    
include 'xajax/xajax_core/xajax.inc.php';

    
/*** a new xajax object ***/
    
$xajax = new xajax();

    
/*** register a PHP function with xajax ***/
    
$rqstButton $xajax->register(XAJAX_FUNCTION'showText');

    
/*** set the request button parameters ***/
    
$rqstButton->setParameter(0XAJAX_JS_VALUE0);

    
/*** process the request ***/
    
$xajax->processRequest();


    function 
showText()
    {
        
/*** the content to assign to the target div ***/
            
$content 'Hello World';

        
/*** a new response object ***/
        
$objResponse = new xajaxResponse();

        
/*** assign the innerHTML attribute to the new $content ***/
        
$objResponse->assign("my_div","innerHTML"$content);

        
/*** return the object response ***/
        
return $objResponse;
    }

    
/*** process the request ***/
    
$xajax->processRequest();

    
/*** the path is relative to the web root mmmk ***/
    
$xajax_js $xajax->getJavascript('/xajax');?>





PHPRO.ORG
echo $xajax_js?>


->printScript(); ?>">Click me
New text will happen here




Manually Calling Requests

In the above code, the javascript to create the onClick event was generated by an object returned by the register() function. While the registration of the function needs to occur, the assigning of the variable does not, and the call could be made manually in the HTML document.


    
/*** include the xajax bootstrap ***/
    
include 'xajax/xajax_core/xajax.inc.php';

    
/*** a new xajax object ***/
    
$xajax = new xajax();

    
/*** register a PHP function with xajax ***/
    
$xajax->register(XAJAX_FUNCTION'showText');

    
/*** process the request ***/
    
$xajax->processRequest();


    function 
showText()
    {
        
/*** the content to assign to the target div ***/
        
$content 'Hello World';

        
/*** a new response object ***/
        
$objResponse = new xajaxResponse();

        
/*** assign the innerHTML attribute to the new $content ***/
        
$objResponse->assign("my_div","innerHTML"$content);

        
/*** return the object response ***/
        
return $objResponse;
    }

    
/*** process the request ***/
    
$xajax->processRequest();

    
/*** the path is relative to the web root mmmk ***/
    
$xajax_js $xajax->getJavascript('/xajax');?>





PHPRO.ORG
echo $xajax_js?>


Click me
New text will happen here




Debugging

Perhaps the most important functionality in the Xajax library is the debug option. When set, the debug option sends a print-out of the whole request process. This will prove invaluable when a script is not behaving as expected.
The debug flag is set, in most instances, immediately after the xajax object is instantiated. This means it will look a little like this.


    
/*** include the xajax bootstrap ***/
    
include 'xajax/xajax_core/xajax.inc.php';

    
/*** a new xajax object ***/
    
$xajax = new xajax();

    
/*** set the debug flag ***/
    
$xajax->setFlag('debug'true);

    
/*** rest of script follows ... ***/
?>

PHP Class functions

PHP Class functions

PHP has available several class functions to help you through the OOP mine field.
  • get_declared_interfaces()
  • class_exists()
  • get_class()
  • get_declared_classes()
Each of these is shown here beginning with the get_declared_interfaces().

get_declared_interfaces()

This helper function provides an array of all the available declared interfaces.

interface fax{
  public function 
dial();
  public function 
send();
  public function 
recieve();
}

interface 
printer{
  public function 
printBlack();
  public function 
printColor();
  public function 
printDraft();
  public function 
kick();
}
/*** our interface implementation ***/class printerFax implements faxprinter{
  public function 
dial(){ }
  public function 
send(){ }
  public function 
recieve(){ }
  public function 
printBlack(){ }
  public function 
printColor(){ }
  public function 
printDraft(){ }
  public function 
kick(){ }
}

  
/*** create and printerfax object ***/
  
$object = new printerFax;
  
/*** get the declared interfaces ***/
  
foreach(get_declared_interfaces() as $key=>$interface)
        {
        echo 
$key.' => '.$interface.'';
        }
?>
The above code should produce a list such as this:

  • 0 => Traversable
  • 1 => IteratorAggregate
  • 2 => Iterator
  • 3 => ArrayAccess
  • 4 => Serializable
  • 5 => RecursiveIterator
  • 6 => OuterIterator
  • 7 => SeekableIterator
  • 8 => Countable
  • 9 => SplObserver
  • 10 => SplSubject
  • 11 => Reflector
  • 12 => fax
  • 13 => printer
From the list above you can see the SPL interfaces available and at the bottom is our fax and printer interfaces. The printerfax is not listed as it is not an interface, rather it is an implentation of an interface.

Other functions

Here we will see three helper functions for our classes
  • get_class()
  • class_exists()
  • get_declared_classes

/*** a pretend class ***/class fax{
  public function 
dial(){ }
  public function 
send(){ }
  public function 
recieve(){ }
}
/*** another pretend class ***/class printer{
  public function 
printBlack(){ }
  public function 
printColor(){ }
  public function 
printDraft(){ }
  public function 
kick(){ }
}
/*** create an instance of the fax class ***/$foo = new fax;
/*** create an instance of the printer class ***/$bar = new printer;

echo 
'$foo is from the ' get_class($foo).' class';
echo 
class_exists("printer").'';
echo 
'Declared classes are: ';
foreach(
get_declared_classes() as $key=>$classname)
    {
    echo 
$key.' -> '.$classname.'';
    }
?>
The little snippet above will produce over one hundred available classes, shortened here for the sake of sanity, such as these below. Note our fax and printer classes at the bottom of the list.
  • $foo is from the fax class
  • 1
  • 0 -> stdClass
  • 1 -> Exception
  • ---8<--- snip ---
  • 106 -> fax
  • 107 -> printer

Autoload

Earlier in this tutorial we stated that the class definition must be included in every call to an object. This is commonly achieved with the include() or require() functions such as below.


/*** include our class definitions ***/include('classes/vehicle.class.php');

include(
'classes/motorcycle.class.php');

include(
'classes/printer.class.php');

include(
'classes/printer.class.php');
/*** instantiate a new vehicle class object ***/$vehicle = new vehicle;

*** 
instantiate a new motorcycle class object ***/$bike = new motorcycle;

*** 
instantiate a new printer class object ***/$printer = new printer;

*** 
instantiate a new fax class object ***/$fax = new fax;
?>
As you can see, this is quite cumbersome. The solution to this sort of mess is __autoload(). The __autoload() function will internally search out the class and load its definition. So the above block of code could be reduced to this.

/*** Autoload class files ***/function __autoload($class){
  require(
'classes/' strtolower($class) . '.class.php');
}
/*** instantiate a new vehicle class object ***/$vehicle = new vehicle;
/*** instantiate a new motorcycle class object ***/$bike = new motorcycle;
/*** instantiate a new printer class object ***/$printer = new printer;
/*** instantiate a new fax class object ***/$fax = new fax;
?>
Now we can load up as many class definitions as we like because they will be autoloaded when we try to use a class that has not been defined. This can save much coding and much searching for code. It is important to remember the naming convention of your classes and class files. Each class file should be named the same as the class definition itself. eg: a class definition file named fax would have the filename fax.class.php
The use of the strtolower() function assures compatibility of naming conventions as windows machines fail to be case sensitive for filenames.

Serializing Objects

We have seen a lot of code above for the use of objects and how they can save us time (and $$$) by re-using them. But what if we needed to somehow store an object for later retrieval, perhaps in a database or in a session variable? PHP has given us the serialize() function to make this rather effortless. There are some limitations, but this can be a very useful tool for applications. Lets see how it performs with a little code.

/*** code here ***/?>

Overloading

Comes a time in every programmers life when...hmm
Overloading in PHP has caused much confusion for no real reason. PHP Overloading can be broken downinto two basic components
  • Method overloading
  • Property overloading
Simply put, Method Overloading is achieved by a special function named __call(). It is available as a sort of method wildcard for calls to undefined methods within a class. This special function is only called when the original method name does not exist. The __call() will only work when the class method you are trying to access does not exist. Lets take it for a spin..

class my_class{
 public function 
foo() {
    return 
"This is the foo function";
 }

/*** end of class ***/

/*** create a new class object ***/
$obj = new my_class;/*** call a non-existant method ***/$obj->bar();?>
Of course the above snippet of code will produce an error such as
Fatal error: Call to undefined method my_class::bar() in /www/overload.php on line 12
because we have called the bar() class method that does not exist. Enter __call(). With the __call() function in place, PHP will try to create the function and you have any code within the _call() method that you like. The __call() method takes two arguements, the method name, and the arguements. Your call to the undefined method may have many arguements and these are returned in an array. Lets put it to the test with two args.


class my_class{
 public function 
foo() {
    return 
"This is the foo function";
 }
  
/*** __call() method with two args ***/
  
public function __call($method$arg){
   echo 
$method.'';
   
print_r($arg);
 }
/*** end of class ***/

/*** create a new class object ***/
$obj = new my_class;/*** call a non-existant method ***/$obj->bar("arg1""arg2");?>
The above code will print the following
bar
Array ( [0] => arg1 [1] => arg2 ) The __call() method has returned the method name that we called along with the array of args passed to it.
Lets now look at we can dynimically manipulate or overload our data.


class readyGetSet {/*** declare $item ***/private $item 'Skate Board';/*** declare the price ***/private $price 100;
/*** our call function ***/function __call($method$arguments){/*** set property and prefix ***/
 
$prefix   strtolower(substr($method03));
 
$property strtolower(substr($method3));

 if (empty(
$prefix) || empty($property))
        {
        return;
        }

if (
$prefix == 'get' && isset($this->$property))
        {
        return 
$this->$property;
        }

if (
$prefix == 'set')
        {
        
$this->$property $arguments[0];
        }
    }
}
$obj = new readyGetSet;

echo 
'Item: ' $obj->getItem() . '';
echo 
'Price: ' $obj->getPrice() . '';
$obj->setItem('CD');$obj->setPrice(25);

echo 
'Item: ' $obj->getItem() . '';
echo 
'Price: ' $obj->getPrice() . '';?>
The second part of overloading refers to properties and the ability to be able to dynamically get and set object properties. The __get() function is called when reading the value of an undefined property, and __set() is called when trying to change that properties value. I hope this is clear as it can get a little confusing... Lets see how it works by example.


 
class candy{
 
/*** declare a property ***/
 
public $type='chocolate';

 
/*** a normal method ***/
 
public function wrap(){
   echo 
'Its a wrap';
 }
 
/*** our __set() function ***/
 
public function __set($index$value){
  echo 
'The value of '.$index.' is '.$value;
 }

/*** end of class ***/

/*** a new candy object ***/
$candy = new candy;/*** set a non existant property ***/$candy->bar 'Blue Smarties';
?>
The result from above will be:
The value of bar is Blue Smarties
Lets see what we have done. We have described a class named candy which contains a public property named $type. It has a simple method and our __set() method. After the class our user code creates a new instance of the candy class. Then we try to set a variable that does not exist in the class. Here the __set method takes control and assigns it for us. We then see in our __set method that it echoes the name of the variable, plus its intended value. The __set() method takes two arguements, the name of the non existant variable, and its intended value.

The __get() method ....



 
class candy{
 
/*** declare a property ***/
 
public $type='chocolate';

 public 
$choctype = array('milk'=>0'dark'=>1'plain'=>2);

 
/*** a normal method ***/
 
public function wrap(){
   echo 
'Its a wrap';
 }
 
/*** our __set() function ***/
 
public function __get($index){
    echo 
'Retrieving element of $choctype property with index of '.$index.'';
     return 
$this->choctype[$index];
 }

/*** end of class ***/

/*** a new candy object ***/
$candy = new candy;/*** set a non existant property ***/
 
echo 'The value of the following element property is '.$candy->milk;
?>
From the above code we get the result
Retrieving element of $choctype property with index of milk
The value of the following element property is 0

Class Constants

You have more than likely seen the use standard constants in PHP. To define a standard constant we use this code:

/*** define an error message ***/
define('_ERROR_MSG', 'An Error has occured!');
/*** echo the constant ***/
echo _ERROR_MSG;
?>
The above snippit would output
An Error has occured!
To define a class constant we use the const keyword.


class my_class {
 
/*** define a class constant ***/
 
const _ERROR_MSG 'An Error has occured!';

public function 
show(){
 echo 
self::_ERROR_MSG;
}

/*** end of class ***/?>
There are now three ways the class constant can be access from this example.
/*** static call to constant ***/echo my_class::_ERROR_MSG;/*** instantiate a class object ***/$my_class = new my_class;/*** can run the show() method ***/$my_class->show();/*** static call to the show method() ***/my_class::show();?>
Each of the above methods would output the same line
An Error has occured!
A class constant, like standard constants, must be exactly as the name suggests, a constant value. It cannot be a variable or the result of a function or method.

Credits

This concludes our little insight into PHP OOP. If you have anything you would like to see here just contact us and we will do our best to help.

PHP - Visibility (public, private, protected)

Visibility (public, private, protected)

The visibility of class members, (properties, methods), relates to how that member may be manipulated within, or from outside the class. Three levels of visibilty exist for class members.
  • public
  • private
  • protected
By default, all class members are public. This means if you do not declare a property or method within the class, it will be public. It is good practice to declare the visibility of class members for the sake of readability for yourself and others. It is much easier for another programmer to see your intentions. This will also future proof your scripts should access modifiers be deprecated.
Public class members (properties and methods) are available through-out the script and may be accessed from outside the class as we demonstrated in our car class. Lets create a simple new class to demonstrate.


class mathematics{/*** a  number ***/public $num;
/**
*
* Add two to a number
*
* @access public
*
* @return int
*
**/
public function addTwo(){
  return 
$this->num+2;
}

}
/*** end of class ***/

/*** Instantiate a new class instance ***/
$math = new mathematics;
/*** set the value of the number ***/$math->num 2;
/*** call the addTwo method ***/echo $math->addTwo();
?>
We can see in the above example that the public variable $num is set from user space and we call a public method that adds two the number and returns the value of $num+2. Having our properties (variables) visible, or accessible from any part of our script works in our favour here, but it can also work against us. A could arise if we lost track of our values and changed the value of $num. To counter this problem we can create a method to set the value for us. Even with this in place it is still possible for somebody to simply access the $num variable. So we make the variable private. This ensures us that the property is only available within the class itself. It is private to the calling class. Consider the following code.



class mathematics{
/*** a  number ***/private $num;
/**
*
* Set the value of $num
*
* @access public
*
* @param $num The number to set
*
* @return int
*
**/
public function setNum($num){
  
$this->num $num;
}
/**
*
* Add two to a number
*
* @access public
*
* @return int
*
**/
public function addTwo(){
  return 
$this->num+2;
}

}
/*** end of class ***/

/*** Instantiate a new class instance ***/
$math = new mathematics;
/*** set the value of the number ***/$math->setNum(2);
/*** call the addTwo method ***/echo $math->addTwo();
?>
?>
Any further attempt to reset the $num property without the setNum() method would result in a Fatal Error such as
Fatal error: Cannot access private property mathematics::$num in /www/mathematics.class.php on line 43
Even if you were to try to access the private $num property from a child class it would fail. This is because private methods and properties in a parent class are not visible to child classes and cannot be accessed. To access a parent method or property from a child class you need to use the protected keyword. Like the private keyword, protetected methods and properties are available only to the class that created them. But unlike private, protected methods and properties are visible from a parent class. Lets see how this works.

class mathematics{/*** a  number ***/protected $num;
/**
*
* Set the value of $num
*
* @access public
*
* @param $num The number to set
*
* @return int
*
**/
public function setNum($num){
  
$this->num $num;
}
/**
*
* Add two to a number
*
* @access public
*
* @return int
*
**/
public function addTwo(){
  return 
$this->num+2;
}

}
/*** end of class ***/
class divide extends mathematics{
/**
*
* Divide a number by two
*
* @access public
*
* @return int
*
**/
public function divideByTwo(){
  
/*** divide number by two ***/
  
$new_num $this->num/2;
  
/*** return the new number and round to 2 decimal places ***/
  
return round($new_num2);
}

/*** end of class ***/

/*** Instantiate a new class instance ***/
$math = new divide;
/*** set the value of the number ***/$math->setNum(14);

echo 
$math->divideByTwo();
?>
We can see here the the user space code has called the setNum() method in the parent mathematics class. This method, in turn, sets the $num property. We are able to do this because the $num property has been declared protected and is visible to the child class.

Final

As we saw in the previous section there are ways to protect your code from being used in an improper manner. Another way of protecting yourself is the Final keyword. Any method or class that is declared as Final cannot be overridden or inherited by another class. Lets put it to the test.

final class mathematics{

/*** end of class ***/
class divide extends mathematics{

}
?>
By running the above code you will get an error such as
Fatal error: Class divide may not inherit from final class (mathematics) in /www/final.php on line 8
This can protect us from those who wish to use our code for a purpose other than that for which it was intended.

Abstract Classes

An abstract class is a class that cannot be instantiated on its own. You cannot create a new object from it. To see this lets make a basic class.

abstract class mathematics{
/**
*
* Add two to a number
*
* @access public
*
* @return int
*
**/
public function addTwo(){
  return 
$this->num+2;
}

/*** end of class ***/

/*** try to create new object from the mathematics class ***/
$math = new mathematics

?>
Using the code above, you will get an error something like this
Fatal error: Cannot instantiate abstract class mathematics in /www/abstract.php on line 23.
As you can see, this is not allowed. Also if you declare any class method to be abstract, you must also declare the class itself as abstract too. So, whats the point you ask? Well, you can inherit from an abstract class. Any class that extends an abstract parent class must create an interface of the parent abstract methods. If this is not done a fatal error is generated. This ensures that the implementation is correct.

abstract class mathematics{/*** child class must define these methods ***/abstract protected function getMessage();

abstract protected function 
addTwo($num1);
/**
*
* method common to both classes
*
**/
public function showMessage() {
  echo 
$this->getMessage();
}

/*** end of class ***/
class myMath extends mathematics{/**
*
* Prefix to the answer
*
* @return string
*
**/
protected function getMessage(){
  return 
"The anwser is: ";
}
/**
*
* add two to a number
*
* @access public
*
* @param $num1 A number to be added to
*
* @return int
*
**/
public function addTwo($num1) {
  return 
$num1+2;
}

/*** end of class ***/

/*** a new instance of myMath ***/
$myMath = new myMath;/*** show the message ***/$myMath->showMessage();/*** do the math ***/echo $myMath->addTwo(4);
?>

Static Methods and Properties

The use of the static keyword allows class members (methods and properties) to be used without needing to instantiate a new instance of the class. The static declaratin must come after the visibility declaration, eg:
public static myClass{
Because there is no object created when using a static call, the keyword $this and the arrow operator, -> are not available. Static variables belong to the class itself and not to any object of that class. To access withing the class itself you need to use the self keyword along with the :: scope resolution operator. Lets whip up a quick example of using static.
/*** a simple class ***/class myClass{/*** a static variable ***/ static $foo;
}
/** give the static variable a value ***/myClass::$foo 'Bar';
/*** echo the static variable ***/echo (myClass::$foo ).?>
The above snippet will echo
Bar This is rather basic as an example, so lets use something practical. Static properties are often used as counters. Here we will use a basic counter class.
class counter{
/*** our count variable ***/private static $count 0;
/**
* Constructor, duh
**/
function __construct() {
  
self::$count++;
}
/**
*
* get the current count
*
* @access public
*
* @return int
*
**/
public static function getCount() {
 return 
self::$count;
}

/*** end of class ***/

/*** create a new instance ***/
$count = new counter(); /*** get the count ***/echo counter::getCount() . '';/*** create another instance ***/$next = new counter(); /*** echo the new count ***/echo counter::getCount().''/*** and a third instance ***/$third = new counter;
echo 
counter::getCount().'';?>
Hopefully by the end of the above snippet you can see what is happening. At each new instance the counter class we increment by one. Not also the use of the :: scope resolution operator and self keyword to refer to the static variable within the class itself.

Interfaces

Interfaces in PHP allow you to define a common structure for your classes. An interface cannot be instantiated on its own. One of the goals of OOP is re-use of code. Interfaces make this a much easier process. The interface methods have no internal logic, they are simply a "mapping" or constraint of what the class, or classes, should implement. Here we will demonstrate how this works using our vehicle class from earlier, with the addition of a stop() function.
class vehicle implements testdrive{
/*** define public properties ***/

/*** the color of the vehicle ***/
public $color;
/*** the number of doors ***/public $num_doors;
/*** the price of the vehicle ***/public $price;
/*** the shape of the vehicle ***/public $shape;
/*** the brand of vehicle ***/public $brand;
/*** the constructor ***/public function __construct(){
  echo 
'About this Vehicle.';
}
/*** define some public methods ***/

/*** a method to show the vehicle price ***/
public function showPrice(){
  echo 
'This vehicle costs '.$this->price.'.';
}
/*** a method to show the number of doors ***/public function numDoors(){
  echo 
'This vehicle has '.$this->num_doors.' doors.';
}
/*** method to drive the vehicle ***/public function drive(){
  echo 
'VRRROOOOOOM!!!';
}
/**
* a method to stop the car
*
* @access public
*
**/
public function stop(){
  echo 
'SSSCCRRREEEEEECCHH!!!';
}

/*** end of class ***/

/*** declare our interface ***/
interface testdrive{/*** some functions that must be implemented ***/function drive();
function 
stop();
}
/*** an new vehicle object ***/$object = new vehicle;
/*** call some methods ***/$object->drive();$object->stop();?>
You may of course create multiple classes to implement your interface, but they will not inherit from each other. When you inherit from a parent class, you may choose to override some of parent methods. If you had multiple parent class methods with the same name, but different functionality or charactaristics, PHP would have no way of telling which of these methods to use. This is why multiple inheritance does not work in PHP. In contrast, classes that implement an interface, must implement every method so there is no ambiguity.
In the real world interfaces provide us with the tools harness parts of multiple classes. Consider this scenario. If we had two classes, one for a fax and the other for a printer. Each has seperate uses and could be described like this:

class fax{
  public function 
dial();
  public function 
send();
  public function 
recieve();
}

class 
printer{
  public function 
printBlack();
  public function 
printColor();
  public function 
printDraft();
}
?>
Both of the above classes give the required usage for each item, but they do not take into consideration the existance of a printer/fax machine. To get the usage of both classes we would do something like this:

class fax{
  public function 
dial();
  public function 
send();
  public function 
recieve();
}

class 
printer extends fax{
  public function 
printBlack();
  public function 
printColor();
  public function 
printDraft();
  public function 
kick();
}

class 
printerFax extends fax{
}
$object = new printerFax;?>
This code works by creating a stack of classes. The grandparent class is fax. Then the printer class extends the fax class and inherits all the methods from that class. This is where some problems may arise. The printer class now has the function dial() available to it which is clearly going to cause some confusion and possibly errors in logic.
To counter this problem an interface can be used to tell the classes what functions (methods) are required. Lets look at the design.

interface fax{
  public function 
dial();
  public function 
send();
  public function 
recieve();
}

interface 
printer{
  public function 
printBlack();
  public function 
printColor();
  public function 
printDraft();
  public function 
kick();
}

class 
printerFax implements faxprinter{
  public function 
dial(){ }
  public function 
send(){ }
  public function 
recieve(){ }
  public function 
printBlack(){ }
  public function 
printColor(){ }
  public function 
printDraft(){ }
  public function 
kick(){ }
}

  
$object = new printerFax;?>
Before we go further, it is recommended you run the above code. It will produce no output but we need to be sure all is well. Having run the code, remove the line
public function kick(){ }
and run it again. What you should now get is an error such as:
Fatal error: Class printerFax contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (printer::kick) in /www/oop.php on line 22
With the kick() function removed from our implementation, we have essentially broken the contract that says we will implement every function (method) specified in the interface. We can gather these functions fractionally from multiple classes, but we MUST have them all or we will get errors such as the one above.
Interfaces play a major role in with SPL and it is recommend you implement the interfaces from SPL and not just the class methods.