PHP Questions about OOP and Software Development principles

In this post, I’ll try to answer questions given by a company for the title “PHP Web Developer”. The questions are all about our field of interest, like SQL and PHP but I’ll try to explain only the PHP with the OOP (Object oriented programming) ones.

Take note here, that these questions has relative brief description, and the idea is to give as much as you can in like 20 or few lines. For everything else, there is Google 😉

Q1: What is the difference between an interface and an abstract class?

A: At first it can scare you, but the concept is very simple. Interfaces are like contracts. The interface accept things that look like the interface wants, and the class using the implemented interface must obey that structure. Don’t forget that interfaces are empty shells. There are only signatures of methods and that implies that the methods of the interface don’t have a body. And last, the interface is like a pattern.

The first difference between the two is that an abstract class first of all is a class. Therefore you can inherit the dependencies and the functionalities from them. An abstract class has all the characteristics of a class. But you cannot instantiate them. The big advantage here is that you can define a behaviour of that abstraction. To make it a little clear, an abstract class can have logic into his methods and you can inherit that behaviour of them.

The second difference is that the abstract class can have static methods, main method and a constructor, and in the abstract class you can create abstract and non-abstract methods, but the interface can have only abstract methods.

Third difference, an interface cannot extend an abstract class, but an abstract class can implement an interface.

The same stands for the properties of the class and the interface.

Q2: What does DRY stand for in programming?

A: DRY stands for “Don’t repeat yourself” and it aims at reducing the repetition of information of all kinds. The definition of the principle states: “Every piece of knowledge must have a single, authoritative representation within a system”. This principle is used not only in PHP but in general. It’s one of the fundamentals, the idea here is simple: Every line of code that goes into an application must be maintained, and is a potential source of future bugs. Duplication needlessly bloats the source code, resulting in adding accidental complexity of the system.

Q3: What does KISS stand for in programming?

A: KISS stands for “Keep it simple, stupid!” And the principle states that a simple solution is better than a complex one, even if the solution looks stupid.

Q4: Which are the main characteristics of OOP?

A: There are like 7-8 as the OOP grows with every moment, but the main are 4.

  • Encapsulation – the idea behind this characteristic is to capture data and keep it safely and securely from outside interference.
  • Inheritance – this is the process by which a class can be derived from a base class with all features of the base class and give some of its own. This increases the code re-usability.
  • Polymorphism – This is the ability to exist in various forms. More info below.
  • Abstraction – The ability to represent data at a very conceptual level without any details

Q5: What is Polymorphism?

A: This is a pattern in OOP in which classes have different functionality while sharing a common interface. Example.

Q6: What is MVC?

A: MVC is a software development architectural pattern that separates an application into three main logical components:

  • Model – the business logic, the validation, the data handler;
  • View – the UI logic, and all user interactions;
  • Controller – the glue between the Model and View. It process all logic and incoming requests.

There are many different types of MVC but the main description is that one above. In a later note, I’ll make a post about it.

Q7: What is the meaning of a final class and a final method?

A: If a method is prefixed by final, it cannot be overridden by the child class method with the same name. If a class is declared as final it cannot be extended, but this doesn’t mean you can’t instantiate it. Just that you cannot extend its functionality.

Q8: Outline the difference between synchronous and asynchronous function execution? 

A: This was a shocker for me at first, because I’ve never heard the terms before my research, but if you notice the question it’s not that scary.

Synchronous function execution is the way that all the programs work. It starts from line one and goes on the next and the next, and so on. And if a function is called in line 5 the execution of the code stops (more like pauses) until the function called has returned it’s message. Whit asynchronous execution the function returns the message immediately, but the program continues with the execution process even if the function, doesn’t have finished it’s purpose.

So in general: When you execute something synchronously, you wait it to finish, return the result, and than move to another task. With asynchronously, you can move to another task before it finishes.

To make it a little clear:
Let say we have 4 process that need to be executed, and we know which one takes a longer time to finish.

A – 20 sec; B – 45 sec; C – 30 sec; D – 65;

They are executed in that particular order: A->B->C->D.

So with synchronous the program will take about 2 and a half minutes to execute.

If we use asynchronous execution and say: let us execute B and C and D like that way it will look something like this:

A starts 20 sec;
B starts after A and simultaneously we start C and D. So the total time will be about minute and 15 seconds, but it take more resources to complete. If a single process takes a thread of the processor will occupy 3 threads for that 1.15 min to be executed and in the first case will take 1 thread but for about 2.5 min to complete.

Q9: What is and how does HTTP work?

A: HTTP (Hypertext Transfer Protocol) is the set of rules for transferring files: (text, graphic images, sound, video and other multimedia files). It has two sides – a client and a server.

The client submits an HTTP request message to the server. The server, which provides resources such as HTML files and other content, or preforms other functions on behalf of the client, returns a response message to the client. The response contains completion status information about the request and may also contain requested content in its message body.

Q10: “Dependency injection”. What’s that about?

A: DI is a technique in which one object donates / supply its dependencies of another object. The dependencies are injected via setter-, constructor- or interface- injection. The idea is to give the client the dependencies needed for completion of an interaction. More on the topic in a subsequent post.

Q11: “Eventual consistency”. What’s that about?

A: Eventual consistency is a characteristic of distributed computing systems such that the value for a specific data item will, given enough time without updates, be consistent across all nodes. Eventual consistency is also known as optimistic replication.

Q12: What are regular expressions and what are they used for?

A: A regular expression is a special text string for describing a search pattern. You are probably familiar with wildcard notation such as *.txt to show all text files in a file manager. The regex equivalent is .*\.txt. Usually this pattern is then used by string searching algorithms for “find” or “find and replace” operations on strings.

Q13: What is n+1 problem and how do you solve it?

A: The n+1 problem occurs when your database queries are not well aligned. And usually when we create a query that has “one to many” relation. Let say this: We have a book, and we have quotes form the book stored into another table in the database. The n+1 approach:

  1. We select the book data from the DB table.
  2. Then for each quote we create a new query to the DB based on the book id.
  3. Total: 5 SQL queries (4 quotes)

The solution is simple

  1. We select the book data.
  2. Then we select all the quotes from that book.
  3. Total: 2 SQL queries (4 quotes).

Q14: Does PHP support multiple inheritance? Explain it.

A: Yes it does, using Traits and Interfaces.

What is a trait? Trait is a mechanism for code reuse. It is similar to a class, but cannot be instantiated on its own. You can use it in a class with the keyword “use”. And in short: Trait is a group of methods that you want to include within another class or classes.

What is an interface? As stated above, the interface is like a contract. And an interface is declared as a class but it has the interface keyword. The class can implement the interface but you cannot call an instance, because the interface is a form of abstraction. All the interfaces’ method must be public.

Q15: What is the difference between public, private and protected?

А: The three scopes of a class.

  • public scope – to make that variable, function, property, method available from anywhere, other classes and other instances of the object.
  • private scope – when you want your variable, function, property, method can be visible in its own class only.
  • protected scope – when you want to make your variable, function, property, method visible in all classes that extend the current class including it’s parent (if there is a extended one)

Q16: What are PSRs?

A: PSR stands for PHP Standard Recommendation. Note one thing here: PSRs are not required, they are recommended. But when you develop something like a service, and you don’t follow the PSRs, there is a great chance that the community will reject it, nevertheless your implementation of this particular service is, to say, a 1000 times faster than any library used.

The official page of PHP’s FIG PSR is here.

Q17: Explain how does a PHP session work.

A: In PHP sessions are started when the script executes the session_start() function. This function generates a random Session ID and stores it in a cookie on the user’s computer.

Note: This is the only session data that is stored on the client side.

The cookie by default is called PHPSESSID. Then the server recognises that cookie, which contains the session ID, so this way it knows which file corresponds to that user.

Q18: What is and how to deal with CSRF (Cross-Site-Request-Forgery)?

A: CSRF is known as session riding and it’s a type of malicious exploit of a website where unauthorised commands are transmitted via a user, that the website has qualified as trusted.

  1. Synchronised CSRF tokens – unique sessions per user; Large random token value; Encrypted token.
  2. Double cookie submit – a double submit cookie is defined as sending a random value and request value match;
  3. Encrypted token pattern – after successful authentication, the server generates a unique Token comprised of the user’s ID, a timestamp value and a nonce, using a unique key available only on the server.
  4. Custom Request Headers – This defence uses only JavaScript to add a custom header, and only within its  origin. By default, browsers don’t allow JavaScript to make cross origin requests.

Q19: What is the difference between == and === for comparison?

A: The first is equal true:

if $var1 is equal to $var2, without checking the type of the variables.

The second is identical true:

if $var1 is equal to $var2, and they are of the same type

Q20: Single quotes (‘) or double quotes (“)? Why?

A: Haven’t thought much about that, but in my common workflow I use mainly double quotes for strings. My idea behind it is that I use the curly braces to isolate the name of the variable and thus it gets evaluated. I use single quotes for array keys, because for me it is more natural. Other main difference between the two is that in the double quoted strings are combinations left from the typewriter era with \n and \r meaning end newline and end row.

Q21: What’s the use of var_dump?

A: It show the information for a given expression that includes it’s type and value. Arrays and objects are shown with indent to show the structure. If the expression is an object it will display the scope also.

Q22: What is the difference between $_GET and $_POST?

A: GET

  • Parameters remain in browser history
  • Can be bookmarked
  • Only application/x-www-form-urlencoded
  • low security
  • Only ASCII chars
  • GET method should not be used when sending passwords or other sensitive information.
  • Can be cached

POST

  • Not saved in history
  • Cannot be bookmarked
  • Uses multipart encoding for binary data
  • better security than $_GET
  • Binary data is allowed and no restrictions in chars
  • POST method used when sending passwords or other sensitive information.
  • Cannot be cached

That’s all for this post. Just some simple questions and simple answers.

Advertisements

2 thoughts on “PHP Questions about OOP and Software Development principles

Give your opinion

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s