PHP interview questions

PHP quiz questions

  • 1.

    Do you use Composer? If yes, what benefits have you found in it?

    Answer:

    Using Composer is a tool for dependency management. You are able to declare the libraries your product relies on and Composer will manage the installation and updating of the libraries. The benefit is a consistent way of managing the libraries you depend on and you will spend less time managing the libraries you depend on in your project.

    View
  • 2.

    What PSR Standards do you follow? Why would you follow a PSR standard?

    Answer:

    You should folow a PSR because coding standards often vary between developers and companies. This can cause issues when reviewing or fixing another developer’s code and finding a code structure that is different from yours. A PSR standard can help streamline the expectations of how the code should look, thus cutting down confusion and in some cases syntax errors.

    View
  • 3.

    What are PSRs? Choose 1 and briefly describe it.

    Answer:

    PSRs are PHP Standards Recommendations that aim at standardising common aspects of PHP Development.

    An example of a PSR is PSR-2, which is a coding style guide. More info on PSR-2 here.

    View
  • 4.

    Why would you use === instead of ==?

    Answer:

    If you would want to check for a certain type, like an integer or boolean, the === will do that exactly like one would expect from a strongly typed language, while == would convert the data temporarily and try to match both operand’s types. The identity operator (===) also performs better as a result of not having to deal with type conversion. Especially when checking variables for true/false you want to avoid using == as this would also take into account 0/1 or other similar representation.

    View
  • 5.

    What does the following code output?

    $i = 016;
    echo $i / 2;

    Answer:

    The Output should be 7. The leading zero indicates an octal number in PHP, so the number evaluates to the decimal number 14 instead to decimal 16.

    View
  • 6.

    What are SQL Injections, how do you prevent them and what are the best practices?

    Answer:

    SQL injections are a method to alter a query in a SQL statement send to the database server. That modified query then might leak information like username/password combinations and can help the intruder to further compromise the server.

    To prevent SQL injections, one should always check & escape all user input. In PHP, this is easily forgotten due to the easy access to $_GET & $_POST, and is often forgotten by inexperienced developers. But there are also many other ways that users can manipulate variables used in a SQL query through cookies or even uploaded files (filenames). The only real protection is to use prepared statements everywhere consistently.

    Do not use any of the mysql_* functions which have been deprecated since PHP 5.5 ,but rather use PDO, as it allows you to use other servers than MySQL out of the box. mysqli_* are still an option, but there is no real reason nowadays not to use PDO, ODBC or DBA to get real abstraction. Ideally you want to use Doctrine or Propel to get rid of writing SQL queries all together and use object-relational mapping which binds your rows from the database to objects in your application.

    View
  • 7.

    How does one prevent the following Warning ‘Warning: Cannot modify header information – headers already sent’ and why does it occur in the first place?

    Answer:

    Do not output anything to the browser before using code that modifies the HTTP headers. Once you call echo or any other code that clears the buffer you can no longer set cookies or headers. That is also true for error messages, so if an error happens before you use the header command and the INI directive display_errors is set then that will also cause that error to show.

    View
  • 8.

    What does MVC stand for and what does each component do?

    Answer:

    MVC stands for Model View Controller.
    The controller handles data passed to it by the view and also passes data to the view. It’s responsible for interpretation of the data sent by the view and dispersing that data to the appropriate models awaiting results to pass back to the view. Very little, if any business logic should be occurring in the controller.

    The model’s job is to handle specific tasks related to a specific area of the application or functionality. Models will communicate directly with your database or other storage system and will handle business logic related to the results.

    The view is passed data by the controller and is displayed to the user.

    Overall, this question is worth knowing as the MVC design pattern has been used a lot in the last few years and is a very good design pattern to know. Even with more advanced flows that go down to repositories and entities, they still are following the same basic idea for the Controller and View. The Model is typically just split out into multiple components to handle specific tasks related to database data, business logic etc. The MVC design pattern helps draw a better understanding of what is being used, as a whole, in the industry.

    View
  • 9.

    What are getters and setters and why are they important?

    Answer:

    Getters and setters are methods used to declare or obtain the values of variables, usually private ones. They are important because it allows for a central location that is able to handle data prior to declaring it or returning it to the developer. Within a getter or setter you are able to consistently handle data that will eventually be passed into a variable or additional functions. An example of this would be a user’s name. If you are not using a setter and just declaring the $userName variable by hand you could end up with results as such: "kevin""KEVIN""KeViN""", etc. With a setter you can not only adjust the value, for example, ucfirst($userName), but you can also handle situations where the data is not valid such as the example where "" is passed. The same applies to a getter – when the data is being returned, you can modify the results to include strtoupper($userName) for proper formatting further up the chain.

    This is important for any developer who is looking to enter a team-based / application development job to know. Getters and setters are often used when dealing with objects, especially ones that will end up in a database or other storage medium. Because PHP is commonly used to build web applications you will run across getters and setters in more advanced environments, even as a junior developer. They are extremely powerful yet not talked about very much. You can really impress an interviewer by knowing what they are and how to use them early on.

    View
  • 10.

    What are the 3 scope levels available in PHP and how would you define them?

    Answer:

    Private – Visible only in its own class
    Public – Visible to any other code accessing the class
    Protected – Visible only to classes parent(s) and classes that extend the current class

    This is important for any developer to know because it shows an understanding that building applications is more than just being able to write code. One must also have an understanding about privileges and accessibility of that code. There are times protected variables or methods are extremely important, and an understanding of scope is needed to protect the integrity of the data in your application along with provide a clear path through the code.

    View
  • 11.

    Suppose that you have to implement a class named Dragonball. This class must have an attribute named ballCount (which starts from 0) and a method iFoundaBall. When iFoundaBall is called, ballCount is increased by one. If the value of ballCount is equal to seven, then the message You can ask your wish is printed, and ballCount is reset to 0. How would you implement this class?

    Answer:

    <?php
    class dragonBall{
      private $ballCount;
    
      public function __construct(){
        $this->ballCount=0;
      }
    
      public function iFoundaBall(){
        $this->ballCount++;
        if($this->ballCount===7){
          echo "You can ask for your wish.";
          $this->ballCount=0;
        }
      }
    }
    ?>

    This question will evaluate a candidate’s knowledge about OOP.

    View
  • 12.

    Suppose you receive a form submitted by a post to subscribe to a newsletter. This form has only one field, an input text field named email. How would you validate whether the field is empty? Print a message "The email cannot be empty" in this case.

    Answer:

    <?php
    if(empty($_POST['email'])){
      echo "The email cannot be empty";
    }
    ?>

    In this question, you will be evaluated on your knowledge about forms management and validation. There is not unique answer for this question, but it must be similar to this one.

    View
  • 13.

    The value of the variable input is a string 1,2,3,4,5,6,7. How would you get the sum of the integers contained inside input?

    Answer:

    <?php
    echo array_sum(explode(',',$input));
    ?>

    The explode function is one of the most used functions in PHP, so it’s important to know if the developer knows this function. There is no unique answer to this question, but the answer must be similar to this one.

    View
  • 14.

    How would you declare a function that receives one parameter name hello?

    If hello is true, then the function must print hello, but if the function doesn’t receive hello or hello is false the function must print bye.

    Answer:

    <?php
    function showMessage($hello=false){
      echo ($hello)?'hello':'bye';
    }
    ?>

    In this question, the interviewer can evaluate if the developer knows how to declare a function and how they would manage the fact of the parameter can or cannot be on the function call. The interviewer can also evaluate if the developer knows the if syntax and if they knows how to print text(echo function).

    View
  • 15.

    How we can get the number of elements in an array?

    Answer:

    The count() function is used to return the number of elements in an array.

    Understanding of arrays and array related helper functions it’s a knowledge that every junior developer should have.

    View
  • 16.

    What are the __construct() and __destruct() methods in a PHP class?

    Answer:

    All objects in PHP have Constructor and Destructor methods built-in. The Constructor method is called immediately after a new instance of the class is being created, and it’s used to initialize class properties. The Destructor method takes no parameters.

    Understanding these two in PHP means that the candidate knows the very basics of OOP in PHP.

    View
  • 17.

    Can the value of a constant change during the script’s execution?

    Answer:

    No, the value of a constant cannot be changed once it’s declared during the PHP execution.

    View
  • 18.

    What are Traits?

    Answer:

    Traits are a mechanism that allows you to create reusable code in languages like PHP where multiple inheritance is not supported. A Trait cannot be instantiated on its own.

    It’s important that a developer know the powerful features of the language (s)he is working on, and Trait is one of such features.

    View
  • 19.

    How can you enable error reporting in PHP?

    Answer:

    Check if “display_errors” is equal “on” in the php.ini or declare “ini_set('display_errors', 1)” in your script.
    Then, include “error_reporting(E_ALL)” in your code to display all types of error messages during the script execution.

    Enabling error messages is very important especially during the debugging process as you can instantly get the exact line that is producing the error and you can see also if the script in general is behaving correctly.

    View
  • 20.

    What is the difference between GET and POST?

    Answer:

    – GET displays the submitted data as part of the URL, during POST this information is not shown as it’s encoded in the request.
    – GET can handle a maximum of 2048 characters, POST has no such restrictions.
    – GET allows only ASCII data, POST has no restrictions, binary data are also allowed.
    – Normally GET is used to retrieve data while POST to insert and update.

    Understanding the fundamentals of the HTTP protocol is very important to have a good start as a PHP developer, and the differences between GET and POST are an essential part of it.

    View

© 2017 QuizBucket.org