Friday 31 May 2013

PHP Interview Questions and Answers for Experienced

PHP Interview Questions and Answers for Experienced

Question: What is Difference between local variable and data members or instance variable?
Answer: 1. A data member belongs to an object of a class whereas local variable belongs to its current scope. 
2. A local variable is declared within the body of a function and can be used only from the point at which it is declared to the immediately following closing brace.
3. Data members are accessible to all member function of the class. Local variable are not accessible in any another function or class.


Question: What are static method? How its different from normal method?
Answer: 1. Static methods are that can be accessed by using the scope resolution operator (i.e ::) and object reference operator ( i.e.-> ).

For example HelloClass::mystatic(); $helloClass->mystatic();
class MyClass{             
    static function mystatic() {                           
        echo "this was declared static!\n";  
    }  
}              
 
$obj = new MyClass();                                                                                 

MyClass::mystatic();
$obj->mystatic();

2. The only rule is that static methods or properties are out of object context.
3. Public function of class can be access by scope resolution operator (i.e ::) and Object Reference Operator (i.e ->) but public data member can't be access through scope resolution operator.




Question: When and Why we use static variable/ functions?
Answer: 1. You use static when you want to use a method / variable that is not tied to an instance.
2. When you want to persistent value throughout multiple call of function.
3. For singleton pattern, we use static method/variable.
4. it is very usefull for caching if a method will be called very often and do just the same thing. For example see below
protected function is_logged_in() {
    static $logged_in = null;
    if($logged_in != null) {
        return $logged_in;
    }

    //Check shibboleth headers
    if (!empty($_SERVER['HTTP_SHIB_IDENTITY_PROVIDER']) || !empty($_SERVER['Shib-Identity-Provider'])) {
        if (!empty($_SERVER[$this->core->dbconfig("shib_auth", self::SHIB_AUTH_CONFIG_UID)])) {
            $logged_in = true;
            return true;
        }
    }
    $logged_in = false;
    return false;
}


Question: What is Persistent Database Connections?
Answer: Persistent connections are links that do not close when the execution of your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses it. If it does not exist, it creates the link.
Persistent connections are good if the overhead to create a link to your SQL server is high. Whether or not this overhead is really high depends on many factors. Like, what kind of database it is, whether or not it sits on the same computer on which your web server sits, how loaded the machine the SQL server sits on is and so forth. The bottom line is that if that connection overhead is high, persistent connections help you considerably.



Question:Server Start/Stop/Restart unix command
Restart Apache web server over the SSH
/etc/init.d/apache2 restart

Stop Apache web server over the SSH
/etc/init.d/apache2 stop

Start Apache web server over the SSH
/etc/init.d/apache2 start

httpd Server restart command
service httpd restart

httpd Server Stop command
service httpd stop

httpd Server Stop command
service httpd start


Question: What is ORM?
Answer: Full form of ORM is Object Relation Mapper.
 ORM is programming technique for converting data between incompatible type systems in object-oriented programming languages.


Data management tasks in object-oriented programming(OOP) are typically implemented by manipulating objects that are almost always non-scalar values.
For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a "Person object" with attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain "PhoneNumber objects" and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance)

Question: What is Exception Handling in PHP?
Answer: Exception Handling is used to handle the error. It can handle all types of error like Warning, Notice, User defined Error message etc but unfortunately it can not handle fatal error. read more...



Question: What is dispatcher in Zend?
Answer: Dispatching is the process of taking the request object,  Zend_Controller_Request_Abstract, extracting the module, controller, action name, and optional parameters contained in it, and then instantiating a controller and calling an action of that controller. If any of the module name, controller name, or action are not found, it will use default values for them.
Zend_Controller_Dispatcher_Standard specifies index for each of the controller and action defaults and default for the module default value, but allows the developer to change the default values for each using the setDefaultController(), setDefaultAction(), and setDefaultModule() methods, respectively.


Question: What is Bootstrap in Zend?
Answer: In Zend Framework, bootstrapping is the process that loads your application. This includes, but is not limited to the Session. Any resources needed by your application to process the request (the dispatch) to the application is bootstrapped/loaded/initialized before the request is fulfilled, e.g. before the controller delegates any input to the model and creates a response that is send back to the client.


Question: What are the advantages and disadvantages of Store procedure.
Answer: Following are the advantage / disadvantage of SP.
Advantage
You do not need to deploy to make a change.
Faster
Easier to expand a system

Disadvantages
Refactoring is harder. Renaming or changing where the store proc is might produce a bad effect.
Unit testing stored proc require code assistance outside the DB



Question : What is difference between array_combine and array_merge?
Answer: array_merge merges the elements of one or more arrays. array_combine  Creates an array by using one array as its keys and another for its values.


Question: How to import database from desktop to server with use of command line?
1) Make a zip of sql dump file and upload the zip file to server through FTP.
2) Login to Putty/Console
3) Go the directory with use of cd command, the location where you have upload the zip file.
4) unizip that zip file, with following command
unzip zipfilename.zip
3)Import the sql dump file with use of following command.
mysql -u username -p databasename < sqlfilename.sql 

(It will for prompt password)


Question: How to copy file from one server to another?
1) Login to Putty/Console
2) Go to the directory where your file exist (suppose file name is file.zip)
3) Use the following command to copy the file frome current server to another server
scp file.zip username@hostname:/foldername
(It will prompt password)
(username, hostname is another server)


Question: How to export database to sql file with use of command line?
1) Login to Putty/Console
2) Execute following commands to export the sql dump into server.
mysqldump –u username –p databasename tablename > sqlfilename.sql
(It will prompt password)


Question: Import database from sql file to mysql
mysql –u username –p databasename tablename < sqlfilename.sql
(It will prompt for password)


Question: What is Responsive web design? 
Responsive web design (RWD) is a web design approach aimed at crafting sites to provide an optimal viewing experience, easy navigation and reading with a minimum of scrolling, resizing and  panning. across a wide range of devices (all mobiles, desktop, laptop, ipad etc).


Question:  What is www1?
World Wide Web
The number(eg 1,2,3,4,5....) that follows the "WWW" indicates that the data being retrieved by the Web browser is gathering the information from a different Web server than the one that serves the typical "WWW" address.
Web sites, especially dynamic Web sites, that handle large amounts of traffic often need more than one server to accommodate the many requests they receive as one server often cannot handle the multitude of requests.
Examples
https://www1.pearsonvue.com/
https://www2.pearsonvue.com/
https://www3.pearsonvue.com/
https://www4.pearsonvue.com/
https://www5.pearsonvue.com/
https://www6.pearsonvue.com/

Here all above websites have same data.


Question: Create a php script that output following.

Answer:
$totalRows =5;
$totalStar=1;
for($rows=1; $rows<=$totalRows; $rows++){
if($rows!=1){
$totalStar+=2;
}
$cols=$totalStar;
$space = $space1 = $totalRows-$rows; 
 
 /** create first space **/ 
  while($space>0){
       echo ' ';
      $space--;
  }
  /** create star **/
    while($cols>0){
       echo "* ";
   $cols--;
  }
  /** create second space **/ 
    while($space1>0){
       echo ' ';
      $space1--;
  }
  
   echo "";

}

Question: What is New Relic. What is benefits of this software?
Answer: New Relic is software as a service (SaaS) that monitors your Website and mobile applications(Android, iOS) in real-time that run in different environments like cloud, on-premise and hybrid. 

Following are few benefits of New Relic
1. Monitoring your website regularly.
2. Downtime Notification by email.
3. Custom Error recording and then report you in email & also can view in newrelic website.
4. Key Transaction tracking: 
You will be able to see where your application is spending most of its time (e.g. in the controller, model OR database).
5. External Service Call Recording (Webservices)



Question: What is Apdex?
Answer: Apdex means Application Performance Index.
It is standard method for reporting & comparing the performance of software.

Purpose:  Analyse the performance, user satisfaction & expectation then Convert into percentage.

Formula
Apdex = (Satisfied + Tolerating / 2) / Total 
Satisfied: Response time is less than or equal to T.
Tolerated: Response time is more than T and (Less than OR Equal to 4T);
Frustrated: Response time is greater than 4T.
T: It is threshold time define by  application owner.

Example: https://docs.newrelic.com/docs/assets/apdex.pdf


Question: Execute a php script using command line in wampserver server in window7.
Answer: Follow  simple steps
1. login to command prompt (CMD)
2. Go to path where "php.exe" exist in wamp folder.
"C:\wamp\bin\php\phpx.x.x";
2. Execute the file with php, for example
php c:/wamp/www/arun/test.php


Question: What is meant by urlencode and urldocode?
Answer: URL coding converts special characters into % signs followed by two hex digits.
For example, urlencode("10.00%") will return "10%2E00%25?
urldocode is just opposite to urlencode


Question: What is difference between unlink and unset?
Answer: unlink: It unlink(remove) the file.
unset: It unlink(remove) the variable from scope.


Question: How to get the image type, size,width and height
Answer: 
type: exif_imagetype()
size: use getimagesize()
width: use imagesx()
height: use imagesy()


Question: What are formating functions in PHP?     
Answer: 
Function                     Description
printf()    :                 Displays a formatted string
sprintf()   :                 Saves a formatted string in a variable
fprintf()   :                 Prints a formatted string to a file
number_format()  :   Formats numbers as strings


Question: How to import Text File in database?
LOAD DATA LOCAL INFILE 'C:/Users/Vijay/Desktop/SQL/image.txt' INTO TABLE images FIELDS TERMINATED BY '|' LINES TERMINATED BY '\n';



Question: How to include a file to a php page?
We can include a file using include() or require() function with file path as its parameter. For Example
include "myfile.php";
require "myfile.php";//use this OR ABOVE



Question: How to detecting request type in PHP (GET, POST, PUT)?
echo $_SERVER['REQUEST_METHOD']; //get/post/put/delete



Question: How to get the full path of php.ini?
You can check php.ini path in phpinfo();
Search with Loaded Configuration File .