Friends

PHP Interview Questions

1. How to get Browser information ?
Using get_browser() we can get the capabilities of the user's browser. This is done by looking up the browser's information in the browscap.ini file. 

echo $_SERVER['HTTP_USER_AGENT'] . "
\n";
$browser = get_browser();
foreach ($browser as $name => $value) {
echo "$name $value 
\n";
}



2. what is final class?
The class which is mentioned as a "final", can not be inherited. So it's methods can not be overridden.
An abstract class can not be a final class as it needs to be extendable.


3. What is abstract class?
Abstract class is a class which can not be instantiated,contains only abstract methods - only method declarations not definitions. Child class must override the methods which are declared as abstract in parent class. These methods must be defined with same (or less restricted) visibility. Also signature should match.



Following is one of the best examples to explain the use of an abstract class and the behavior of it.
01class Fruit {
02private $color;
03
04public function eat() {
05 //chew
06}
07
08 public function setColor($c) {
09  $this->color = $c;
10 }
11}
12
13class Apple extends Fruit {
14 public function eat() {
15  //chew until core
16 }
17}
18
19class Orange extends Fruit {
20 public function eat() {
21  //peel
22  //chew
23 }
24
}
Now taste an apple
1$apple new Apple();
2$apple->eat();

What’s the taste of it? Obviously it’s apple

Now eat a fruit

1$fruit new Fruit();
2$fruit->eat();

What’s the taste of it? It doesn’t make any sense. does it? Which means the class fruit should not be Instantiable . This is where the abstract class comes into play

1abstract class Fruit {
2 private $color;
3
4 abstract public function eat()
5
6 public function setColor($c) {
7  $this->color = $c;
8 }
9}



4. OverView of Drupal CMS 

Basically, there are 5 main layers in Drupal where information flows,

  1. Data (Node, ETC)
  2. Modules
  3. Blocks and Menus
  4. User Permissions
  5. Template

Data - Base of the system is collection of Nodes. – the data pool

Modules -These are functional plugins that are either part of the Drupal core (they ship with Drupal) or they are contributed items that have been created by members of the Drupal community.

Blocks and Menus - This is the next layer where we find blocks and menus. Blocks often provide the output from a module or can be created to display whatever you want, and then can be placed in various spots in your template (theme) layout. Blocks can be configured to output in various ways, as well as only showing on certain defined pages, or only for certain defined users.

User Permissions - Here is the next layer where settings are configured to determine what different kinds of users are allow to work and see.

Template - This is mainly the site theme or the skin. This is made up predominantly of XHTML and CSS, with some PHP variables intermixed.

5. What are the two new error levels introduced in PHP5.3?

E_DEPRECATED - The E_DEPRECATED error level is used to indicate that a function or feature has been deprecated.

E_USER_DEPRECATED - The E_USER_DEPRECATED level is intended for indicating deprecated features in user code, similarly to the E_USER_ERROR and E_USER_WARNING levels.

5. Explain Late Static binding.


01class A {
02    public function who() {
03        echo __CLASS__;
04    }
05    public function test() {
06        $this->who();
07    }
08}
09
10class extends A {
11    public function who() {
12        echo __CLASS__;
13    }
14}
15$obj new B;
16$obj->test();
Out put of the above snippet is? B This is mainly because we have the object instance named as $this is for the class B, though the function is instantiated inside class A. But, If you need the expected output which is “A”, we can call them statically as follows
01class A {
02    public static function who() {
03        echo __CLASS__;
04    }
05    public static function test() {
06        self::who();
07    }
08}
09
10class extends A {
11    public static function who() {
12        echo __CLASS__;
13    }
14}
15
16B::test();
Out put -> A
Main limitation of self:: or __CLASS__ are resolved using the class in which the function belongs, as in where it was defined. By introducing late static binding this limitation has been resolved as follows,
01class A {
02    public static function who() {
03        echo __CLASS__;
04    }
05    public static function test() {
06        static::who(); // Here comes Late Static Bindings
07    }
08}
09
10class extends A {
11    public static function who() {
12        echo __CLASS__;
13    }
14}
15
16B::test();
Out put -> B


Quick Guide : Design Patterns for PHP - part III

The observer pattern
why?
To define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
One object makes itself observable by adding a method that allows another object, the observer, to register itself. When the observable object changes, it sends a message to the registered observers.

The participants classes in this pattern are:
Observable - interface or abstract class defining the operations for attaching and de-attaching observers to the client. 
ConcreteObservable - concrete Observable class. It maintain the state of the object and when a change in the state occurs it notifies the attached Observers.
Observer - interface or abstract class defining the operations to be used to notify this object.

A simple example is a list of users in a system. The code in Listing 4 shows a user list that sends out a message when users are added. This list is watched by a logging observer that puts out a message when a user is added.
Listing 4. Observer.php

<?php
interface IObserver
{
  function onChanged( $sender, $args );
}

interface IObservable
{
  function addObserver( $observer );
}

class UserList implements IObservable
{
  private $_observers = array();

  public function addCustomer( $name )
  {
    foreach( $this->_observers as $obs )
      $obs->onChanged( $this, $name );
  }

  public function addObserver( $observer )
  {
    $this->_observers []= $observer;
  }
}

class UserListLogger implements IObserver
{
  public function onChanged( $sender, $args )
  {
    echo( "'$args' added to user list\n" );
  }
}

$ul = new UserList();
$ul->addObserver( new UserListLogger() );
$ul->addCustomer( "Jack" );
?>


Output:

% php observer.php 
'Jack' added to user list
%

This code defines four elements: two interfaces and two classes. The IObservable interface defines an object that can be observed, and the UserList implements that interface to register itself as observable. The IObserver list defines what it takes to be an observer, and the UserListLogger implements that IObserver interface. This is shown in the UML in Figure 4.

Figure 4. The observable user list and the user list event logger
The observable user list and the user list event logger


The test code creates a UserList and adds the UserListLogger observer to it. Then the code adds a customer, and the UserListLogger is notified of that change.
It's critical to realize that the UserList doesn't know what the logger is going to do. There could be one or more listeners that do other things



In next post I will explain the forth design pattern "The chain-of-command pattern".



Quick Guide : Design Patterns for PHP - part II

The Singleton Pattern

Why?
1. If are using a reference to an object in mulitple location and you don't want the overhead of creating a new instance of that object for each refrence
e.g. Database connection object
2. To pass the objects state from one reference to another instead of starting from an initial state.

The singleton pattern covers this need. An object is a singleton if the application can include one and only one of that object at a time.

<?php
require_once("DB.php");

class DatabaseConnection
{
  public static function get()
  {
    static $db = null;
    if ( $db == null )
      $db = new DatabaseConnection();
    return $db;
  }

  private $_handle = null;

  private function __construct()
  {
    $dsn = 'mysql://root:password@localhost/photos';
    $this->_handle =& DB::Connect( $dsn, array() );
  }
  
  public function handle()
  {
    return $this->_handle;
  }
}

print( "Handle = ".DatabaseConnection::get()->handle()."\n" );
print( "Handle = ".DatabaseConnection::get()->handle()."\n" );
?>


Output
% php singleton.php 
Handle = Object id #3
Handle = Object id #3
%
This code shows a single class called DatabaseConnection. You can't create your own DatabaseConnection because the constructor is private. But you can get the one and only one DatabaseConnection object using the static get method.

The database connection singleton
The two handles returned are the same object. If you use the database connection singleton across the application, you reuse the same handle everywhere.
You could use a global variable to store the database handle, but that approach only works for small applications. In larger applications, avoid globals, and go with objects and methods to get access to resources.

In next post I will explain the third design pattern "The observer pattern".

Quick Guide : Design Patterns for PHP


Design pattern provides useful ways for developing robust software faster along  with a way of encapsulating large ideas in friendly terms.  Most of the PHP programmer are not ware of the design patterns and how to implement those. So instead of going through the history and wasting more time in explanation, I will brief those patterns in short cut with examples.

The Factory pattern
The factory pattern is a class that has some methods that create objects for you. Instead of using new directly, you use the factory class to create objects. That way, if you want to change the types of objects created, you can change just the factory. All the code that uses the factory changes automatically.

What's the need to use Factory pattern?
Problem is tight coupling - Functions and classes in one part of the system rely too heavily on behaviors and structures in other functions and classes in other parts of the system. lots of code relies on a few key classes. Difficulties can arise when you need to change those classes. For example, suppose you have a User class that reads from a file. You want to change it to a different class that reads from the database, but all the code references the original class that reads from a file.

<?php
interface IUser
{
  function getName();
}

class User implements IUser
{
  public function __construct( $id ) { }

  public function getName()
  {
    return "Jack";
  }
}

class UserFactory
{
  public static function Create( $id )
  {
    return new User( $id );
  }
}

$uo = UserFactory::Create( 1 );
echo( $uo->getName()."\n" );
?>


Output
% php factory1.php 
Jack
%


Figure 1. The factory class and its related IUser interface and user class
The factory class and its related IUser interface and user class 

Advantage

suppose you need to first create the object and then set many attributes. This version of the factory pattern encapsulates that process in a single location so that the complex initialization code isn't copied and pasted all over the code base.

Listing 2. Factory2.php
<?php
interface IUser
{
  function getName();
}

class User implements IUser
{
  public static function Load( $id ) 
  {
        return new User( $id );
  }

  public static function Create( ) 
  {
        return new User( null );
  }

  public function __construct( $id ) { }

  public function getName()
  {
    return "Jack";
  }
}

$uo = User::Load( 1 );
echo( $uo->getName()."\n" );
?>


Output:

% php factory2.php 
Jack
%


Figure 2. The IUser interface and the user class with factory methods
The IUser interface and the user class with factory methods 









In my next part II will explain the Singleton pattern.


Part-II

Twitter Delicious Facebook Digg Stumbleupon Favorites More