PHP interview

From Hawk Wiki
Jump to: navigation, search

Basic

Protected

A protected access specifier is mainly used with inheritance. A data member or member function declared as protected will be accessed by its class and its base class but not from the outside world (i.e. rest of the script). We can also say that a protected data member is public for the class that declares it and it’s child class; but is private for the rest of the program (outside world).

abstract class

Can not be Instantiable.(cannot become instance. Can only be inherited)

abstract class Fruit {
 private $color;

 abstract public function eat()

 public function setColor($c) {
  $this->color = $c;
 }
}

Difference between Abstract Class and Interface
Abstract Classes

An abstract class can provide some functionality and leave the rest for derived class
The derived class may or may not override the concrete functions defined in base class
The child class extended from an abstract class should logically be related

Interface

An interface cannot contain any functionality. It only contains definitions of the methods
The derived class must provide code for all the methods defined in the interface
Completely different and non-related classes can be logically be grouped together using an interface

Polymorphism

Why method polymorphism cannot be achieved
The reason why polymorphism for methods is not possible in PHP is because you can have a method that accepts two parameters and call it by passing three parameters. This is because PHP is not strict and contains methods like func_num_args() and func_get_arg() to find the number of arguments passed and get a particular parameter.

Because PHP is not type strict and allows variable arguments, this is why method polymorphism is not possible.

PHP 5 Polymorphism
Since PHP 5 introduces the concept of Type Hinting, polymorphism is possible with class methods. The basis of polymorphism is Inheritance and overridden methods.

Single or Double Quotes?

//Sometimes people use double quotes in PHP to avoid having to use the period to separate code. For example, you could write:
$color='red';
echo "I have a $color shirt on today<br/>";
//Faster however is not always better. A better way to write this code would be:
echo 'I have a ' .$color. ' shirt on today<br/>';
echo 'I have a $color shirt on today<br/>';

Output:

I have a red shirt on today
I have a red shirt on today
I have a $color shirt on today

Avoid Mysql Injection

$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
$passwd=mysql_real_escape_string($_POST['password']);
$passwd1=addslashes($_POST['password']);
echo $passwd."<br />";
echo $passwd1."<br />";
echo ($query);

Output

\' OR \'\'=\'
\' OR \'\'=\'
SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''

This would allow anyone to log in without a valid password.

Static method

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class.

<?php
class Foo
{
    public static $my_static = 'foo';

    public function staticValue() {
        return self::$my_static;
    }
}

class Bar extends Foo
{
    public function fooStatic() {
        return parent::$my_static;
    }
}


print Foo::$my_static . "\n";

$foo = new Foo();
print $foo->staticValue() . "\n";
print $foo->my_static . "\n";      // Undefined "Property" my_static 
print $foo::$my_static . "\n";
$classname = 'Foo';
print $classname::$my_static . "\n"; // As of PHP 5.3.0

print Bar::$my_static . "\n";
$bar = new Bar();
print $bar->fooStatic() . "\n";

Final

final classs: Cannot be inherited (extended)
final function: Cannot be overidden by subclasses.

Advanced

Magic Methods

  • __constructor() __destructor()
  • __toString()
    <?php
    
    class Customer {
    private $firstName, $lastName, $email;
    
    public function __construct($firstName, $lastName, $email) {
    $this->firstName = $firstName;
    $this->lastName = $lastName;
    $this->email = $email;
    }
    
    public function __toString() {
    return “Debug message from Customer Class : First Name = ” . $this->firstName . “, Last Name = ” . $this->lastName . “, Email = ” . $this->email;
    }
    }
    
    $c = new Customer(“Sunil”,”Bhatia”,”email@domain.com”);
    
    echo “Customer Object is >>” . $c;
    
    ?>
    
  • __set() __get() __isset() __unset()
    Because of the above limitation, PHP engine provides two magic methods __get() and __set(). __get() is used when value from an undefined variable is to be read and __set() is used when a value is to be assigned to a undefined variable of a class.
  • The magic method __call() is to undeclared methods
  • The magic method __autoload() is not included in your class definition as this is to be called once in a script. The best place to put the autoload() file is in your configuration file which is loaded in all your other scripts.
    function __autoload($class) {
       require $class . '.php'; //is substituted as require Customer.php (with capital 'C')
    }
    //In the above program, we don’t explicitly include customer.php and orders.php file. When an instance of the customer class is to be created, the PHP engine checks to see if the file Customer.php is loaded. It does not raise an warning on finding that Customer.php has not been loaded, it in turn calls the magic method __autoload(). The __autoload() magic method accepts a parameter which is the name of the class that needs to be loaded.
    
  • __sleep() magic method is called when the object of a class is about to be serialized
  • __clone()
    To clone an object means to create a duplicate of an object. With regular variables $a = $b means that a new variable $a gets created that contains the value of $b. This means that 2 variables get created.
    With objects $obj2 = $obj1 does not mean that a new object i.e. $obj2 gets created. When we execute $obj2 = $obj1, the reference of $obj1 is assigned to $obj2. This means that $obj1 and $obj2 point to the same memory space. Look at the diagram below.
    class Customer {
    	private $name;
     
    	public function setName($name) {
    		$this->name = $name;
    	}
     
    	public function getName() {
    		return $this->name;
    	}
     
    	public function __clone() {
    		$c = new Customer();
    		$c->setName($this->name);
    		return $c;
    	}
     
    }
    $o2 = clone $o1;
    

    MVC

    http://www.tonymarston.net/php-mysql/model-view-controller.html Input --> Processing --> Output Controller --> Model --> View

    Model

    A model is an object representing data or even activity, e.g. a database table or even some plant-floor production-machine process. The model manages the behavior and data of the application domain, responds to requests for information about its state and responds to instructions to change state. The model represents enterprise data and the business rules that govern access to and updates of this data. Often the model serves as a software approximation to a real-world process, so simple real-world modeling techniques apply when defining the model. The model is the piece that represents the state and low-level behavior of the component. It manages the state and conducts all transformations on that state. The model has no specific knowledge of either its controllers or its views. The view is the piece that manages the visual display of the state represented by the model. A model can have more than one view. Note that the model may not necessarily have a persistent data store (database), but if it does it may access it through a separate Data Access Object (DAO).

    View

    A view is some form of visualisation of the state of the model. The view manages the graphical and/or textual output to the portion of the bitmapped display that is allocated to its application. Instead of a bitmapped display the view may generate HTML or PDF output. The view renders the contents of a model. It accesses enterprise data through the model and specifies how that data should be presented. The view is responsible for mapping graphics onto a device. A view typically has a one to one correspondence with a display surface and knows how to render to it. A view attaches to a model and renders its contents to the display surface. Controller

    A controller offers facilities to change the state of the model. The controller interprets the mouse and keyboard inputs from the user, commanding the model and/or the view to change as appropriate. A controller is the means by which the user interacts with the application. A controller accepts input from the user and instructs the model and view to perform actions based on that input. In effect, the controller is responsible for mapping end-user action to application response. The controller translates interactions with the view into actions to be performed by the model. In a stand-alone GUI client, user interactions could be button clicks or menu selections, whereas in a Web application they appear as HTTP GET and POST requests. The actions performed by the model include activating business processes or changing the state of the model. Based on the user interactions and the outcome of the model actions, the controller responds by selecting an appropriate view. The controller is the piece that manages user interaction with the model. It provides the mechanism by which changes are made to the state of the model.