You get a bonus - 1 coin for daily activity. Now you have 1 coin

PHP Interview Questions and Answers

Lecture



  PHP Interview Questions and Answers The fact that you are a good programmer plays a strikingly small role in the interview process. In order for your work to be productive, you need to be able to solve enormous, problem-prone problems for weeks and months. Each question on the interview, on the contrary, lasts less than one hour. In order to show yourself well in an interview, you need to know how to quickly solve small problems under pressure, while clearly stating your thoughts. This is a completely different skill (at the same time, I don’t say that the ability to easily solve tasks at an interview has no connection with programming skills. Simply, this connection is expressed much weaker than many companies believe, and it is other factors that differ from specialized skills explains such an impressive discrepancy).

Moreover, interviewers often do this unprofessionally and somewhat absently (they would prefer to do programming instead of an interview), and therefore ask questions that are not related to the actual workflow. As a result, in the course of the interview, candidates are confronted with a biased attitude, lack of standardization and issues in comparison with the sample.

The good news is that interviewing is the skill that can be learned. By and large, that good programmers are not required to acquire special skills that help to successfully pass the interview. But nothing can be done about the status quo. In the meantime, if you want to make the best impression on your job interview, this post will tell you how, in our opinion, to achieve this most effectively.

1. Show enthusiasm


Enthusiasm has a huge impact on job interview results. About 50% of our candidates who did not pass further interviews in companies failed them not for technical reasons. Companies usually explain this by saying that a person “does not fit into the company's culture.” However, in nine out of ten cases “to fit into culture” is to show enthusiasm in what the company does. Companies hire people who have a keen interest in their mission. For many, this is just as important as technical knowledge. And that makes sense. Motivated employees will feel happier and work harder.

The problem is that it can be played. Some candidates manage to convince every company in which they are interviewed that they have only dreamed about this job all their lives, while others (sincerely motivated and interested in work) cannot convey their true aspirations. We meet again and again with this. The solution here is one for everyone - learn how to show your enthusiasm. This does not mean that you are allowed to cheat. An interview is like a first date. No one wants to hear on the first date that he is only one of many options, even though it usually is. So here, most programmers just want to have a good job with a decent salary. But to start with this interview should not be. It is best to prepare notes before the interview about what you like in the company, and to mention this when the person conducting the interview asks if you have any questions. A good source of ideas may be reading recent posts in the company's blog and press releases, then you can mention the materials that you found most interesting.

This idea seems rather superficial. I think that by reading this, you yourself agree. But (and anyone who has ever interviewed will tell you the same thing) the percentage of candidates who do this is amazingly small. If you carefully prepare notes on why you find the company interesting, it will really increase the likelihood of your passing. You can even refer to your notes during the interview - this will show that you are preparing.

2. Study the terms commonly used in interviews.


A huge percentage of questions asked at the interview concerns the data structure and algorithms. It's true. We collect information from candidates about the questions asked during interviews at YC companies, and more than 70% of the questions are about algorithms. You do not need to be an expert, but knowing the list of algorithms and data structures below will help you get a job at most companies.

  • Hash tables
  • Related Lists
  • Search in width, search in depth
  • Quick sort, merge sort
  • Binary search
  • 2D sets
  • Dynamic arrays
  • Binary search tree
  • Dynamic programming
  • Big-O analysis


Depending on your education and previous work, this list may be either simple or completely intimidating. These concepts are much more common at interviews than in reality in web programming. If you are self-taught or have graduated from an educational institution long ago, and these concepts are unfamiliar to you, then you should study them for a successful interview. Even if all this is not new to you, it will not hurt to refresh your knowledge anyway. An amazingly large percentage of questions at the interview is reduced to a search in width or using a hash table for counting unique elements. You should be able to write a BFS algorithm and understand how hash tables are involved.

Learning all this is not as difficult as many people with whom we have spoken. Algorithms are usually explained in scientific language, and this can be confusing. But in essence, nothing from this list is more complicated than the architecture of a modern web application. If you can (well) build a web application, then you can learn this too. For my part, I can recommend the book by Steven Skiena entitled “Algorithms. Development Guide "(The Algorithm Design Manual). This material is beautifully presented in Chapters 3–5 - simple and accessible. Yes, the book uses C and mathematical syntax, but it perfectly reveals the topic. On Coursera you can also find some good courses on algorithms. In this course, in particular, attention is paid to concepts whose knowledge is important during the interview.

The study of algorithms and data structures helps not only because the material is necessary for success at the interview, but also because the approach to the problems taken in the course of the algorithm is the same approach that works best in the interview. Learning algorithms will help you get the right mindset for the interview.

3. Use the help of your interviewer


Interviewers help candidates. They give hints, react to ideas and usually guide the interview process. But they do not help all candidates equally. Some programmers are able to get considerable help in such a way that the person who conducts the interview will not reproach them. Others are condemned for any hints they receive. Believe me, you want to be helped.

It depends on how communication develops. If your interviewer likes your approach and you find a common language with him, he will be happy to help you. You can achieve this by developing a specific interview algorithm. I recommend the following steps:

  • Ask questions
  • Discuss the solution to the problem "in the forehead"
  • Discuss an optimized solution
  • Write the code


After you have been asked a question, start by defining what you are being asked about. This is the moment when you have to be pedantic. Clarify all the ambiguities that you find. Ask about borderline cases. Give specific examples to start solving the problem and make sure that you understand what the final result is expected of you. Ask questions, even if you are practically confident in the answers. This is useful because it gives you the opportunity to find out borderline cases and get all the data needed to solve the problem (the candidate’s ability to work with borderline cases is one of the key aspects that interviewers take into account for the overall assessment of the interview). In addition, it gives you time to gather your thoughts before you begin to solve the problem.

Next, you need to talk about the simplest solutions to problems that only come to your mind. You should speak and not take up writing code immediately, so if you verbally explain your ideas, you can quickly answer the question and move on to the next one, and this will involve the interviewer himself, who in turn can help by guiding you. If you go straight to writing code, you will lose this opportunity.

Candidates often skip the first step, believing that the simplest solution to a problem is either too obvious or wrong. It is not right. Make sure that you always find solutions to the problems you are facing (even if you need to use exponential time or the NSA supercomputer). After you have described such a simple solution, ask the interviewer if he wants to implement it or you should come up with a more expedient solution. As a rule, you will be asked about the latter.

As for a more expedient decision, state your thoughts, as for the first time. Again, talk instead of writing code, and throw ideas at the interviewer. It is hoped that the question will be similar to anything you have already seen, and you will know the answer to it. If not, then you should think about the most similar problems in this case you faced, and on the basis of this build your answers. Most of the questions at the interview are related to slightly veiled applications of the classic CS algorithms. Often the interviewer will lead you to this algorithm, but only if you start the process yourself.

And finally, after both you and the interviewee agree that you have a good solution, you should start writing the code. Depending on the company, you will write the code either on the computer or on the blackboard. But since you already have a solution, the task before you should not look like something intricate. For extra points, ask your interviewer if he wants you to write tests.

4. Talk about solutions


An interview for a programmer’s position usually consists of questions directly related to programming, and it was about them that I mentioned earlier in this article. At the same time, you may encounter questions about creating a specific system. Companies seem to be inclined to “torture” in this way more experienced candidates. In this case, the potential employee is asked how they would develop this or that complex system for applying to real data. As examples, use the development of Google Maps, social networks, or, for example, the creation of API for the bank.

The first observation: the answer to questions related to the development of such a system requires specific knowledge. No one will require you to create Google Maps (it took a lot of time from many people). At the same time, the interviewer expects from the candidate some understanding of the basic principles for developing such a system. Do not worry, usually all such questions are related to the backend, so you can make significant progress if you understand the relevant information well. Here is an incomplete list of what is recommended to study before the interview:

  • HTTP (protocol level)
  • Databases (indexes, query scheduling)
  • Content Delivery Networks (CDN)
  • Work with cache (LRU cache, memcached, Redis)
  • Load balancing systems
  • Distributed Worker Systems


You need to not only learn these terms, but also understand how they interact with each other, forming real systems. The best way to learn these concepts is to read about how other programmers have implemented these tools. High Scalability blog is the best for such reading. This resource publishes detailed materials about a particular backend architecture in a particular existing company. This way you can find out how each solution from the list above is used in real systems.

As soon as you are finished with reading, the answers to the questions on the creation of such systems will turn into the sequential execution of a given algorithm for you. Start from the highest level and then gradually go down. At each level, ask the interviewer about the requirements (do you need to present a simple initial stage of development, or should you tell how a complete system will look like?) And talk about several options (for example, you can use ideas drawn from online materials). Discussion of various options and trade-offs in solving problems is the key to success. For the interviewer, it’s actually not so important whether you can build a good system. He is more interested in how skillfully you can talk about finding the optimal solution by analyzing the advantages and disadvantages of the proposed options. Practice such talk.

5. Emphasize your work.


The third type of questions you may encounter at the interview relate to your professional experience. Here the interviewer usually asks the candidate to tell about completed projects. The mistake of many programmers is that they talk exclusively about the technical side of a project. So, most experts talk about the successful implementation of a neural network classifier or the implementation of a bot to check grammar on Twitter. This is not the best choice because it is very difficult for the interviewer to judge the scope of the project. Many candidates talk about various side projects, exaggerating their significance, and the interviewer has no way to check if he hears the truth or beautiful lies.

In this case, the optimal solution is to choose a project that showed specific results and emphasize them. Here you often have to sacrifice a more interesting (technical point of view) project, but believe me, it's worth it. Think (in advance) about the project that showed the most "tangible" results in the real world. If you created a game for iOS, and it scored 50 thousand downloads, this is the figure that should be voiced. Or, for example, you, while undergoing internship at a company, wrote an interface for access to the “admin area”, which you later decided to use for the work of all administrators. The fact of using the result of your activity is an excellent reason to tell about your achievement. In addition, choosing a more “technical” project when answering a question about your past accomplishments sends the company information that you are focused on the work itself. Programmers who are more interested in the “technical” side of each project, rather than the results achieved, are usually eliminated at the initial stage of recruitment (it is believed that sometimes such specialists are not productive enough).

6. Use a dynamic programming language, but be sure to mention C


I recommend that you use dynamic languages ​​such as Python, Ruby, or JavaScript for your interviews. Of course, you should use any language that you know best. But we found that many interviewers prefer C, C ++ or Java, for some reason believing that they are the "real" programming languages. Several classic interviewing books recommend that programmers choose Java or C ++. But it seems to us that, at least for startups, this is bad advice. Candidates do better with dynamic languages. In my opinion, this is due to their compact syntax, flexible typing, as well as list and hash literals. These are weak programming languages. There may be some difficulties with them when creating complex systems (which is also a very controversial issue), but they are good when you try to stick a binary search algorithm right on the board.

No matter what language you use, it is worth mentioning that you worked with other languages. Companies have prejudices about specialists who speak only one programming language. If you know only one language, you must rely on the fact that you are really good at it. But if you have done something for major or third-party projects in several languages, be sure to tell about this non-interview. If you have worked with computer-oriented languages ​​like C, C ++, Go or Rust, then the mention of this is especially important.

Java, C # and PHP are problematic to some extent. We found that startups have some preconceptions about these languages. We have data that show that programmers using these languages ​​in interviews get lower marks. This is unfair, but it is true. If you have other options, I recommend not using these languages ​​in interviews for startups.

7. Practice, practice and practice again.


Вы сможете лучше выглядеть на собеседовании, если заранее будете репетировать ваши ответы. Все потому, что любое собеседование — это стресс, а стресс негативно влияет на то, как вы себя преподаете. Решение одно — практика. Собеседования становятся менее трудными, когда вы приобретаете опыт в этом деле и со временем к ним привыкаете. Мы часто замечаем, что первые интервью кандидатов (даже в рамках одного поиска работы) оказываются неудачными, однако затем они обретают уверенность и лучше выглядят на интервью. Есть вам нелегко побороть стресс, то я рекомендую начать с инициирования собеседования. Найдите список вопросов для собеседования (рекомендуем книгу Cracking the Coding Interview, на российском рынке известную под названием «Карьера программиста. Как устроиться на работу в Google, Microsoft или другую ведущую IT-компанию») и проработайте их. Установите таймер, уделяя на каждый вопрос по 20 минут и старайтесь ответить на него как можно быстрее. Потренируйтесь писать ответы на доске (не все компании этого требуют, но это самый худший вариант, который стоит отработать). Лист бумаги и ручка могут послужить вам для симуляции доски. Если у вас есть друзья, которые могут помочь вам потренироваться проходить собеседование, то это замечательно. Вы можете собеседовать друг друга по очереди. Чтение задаваемых на интервью вопросов также даст вам неплохие идеи, которыми вы можете воспользоваться во время реального собеседования. На удивление очень много вопросов используются повторно (целиком или частично).

Даже опытные (и не подверженные стрессу) кандидаты извлекут из этого выгоду. Прохождение собеседования — это навык, который существенно отличается от работы программиста, и этот навык может атрофироваться. Но опытные программисты часто (и обоснованно) чувствуют, что им не стоит готовиться к интервью. Они учатся меньше. Именно поэтому более молодые кандидаты часто фактически лучше отвечают на вопросы, нежели опытные кандидаты. Компании знают это, и, как это ни парадоксально, некоторые сообщают нам, что для опытных кандидатов они устанавливают более низкий проходной порог ответов на вопросы о программировании.

8. Упомяните о своем послужном списке


Послужной список изначально очень важен для интервьюеров. Наши кандидаты, которые ранее работали в ведущих компаниях или учились в лучших учебных заведениях, успешно проходят собеседования на 30% чаще, нежели те, которые не могут этим похвастаться (актуально для определенного уровня квалификации по результатам исследования, не учитывающего громкие названия компаний из резюме кандидатов). Мне это не нравится. Это не отвечает принципам меритократии, и это полный отстой, но, если в вашем послужном списке нечто подобное имеется, то в ваших же интересах сообщить об этом интервьюерам. Вы не должны слепо полагаться на то, что они прочитают ваше резюме.

9. Собирайте сделанные вам предложения работы


Если вы когда-нибудь почитаете советы по привлечению инвестиций для основателей, то вы узнаете о том, что самое трудное — это получить предложение от первого инвестора. Как только вы его получили, то посыплются и другие. Это же правило применимо и к предложениям работы. Если у вас уже есть предложение работы, то не забудьте упомянуть об этом на интервью — это оказывает сильное влияние на интервьюера, склоняя его в вашу пользу.

И поэтому стоит воспользоваться следующей стратегией: сделать список интересующих вас компаний и назначать время собеседований в обратном порядке относительно степени вашего интереса. Тогда то, что вы неплохо себя покажете ранее, позднее увеличит ваши шансы получить работу, которая для вас интереснее всего. Вам определенно стоит так сделать.

итак посмотрим примеры впросов на собеседваниях

1. What is the >

2. Ways to set comments in PHP

3. Print data types that PHP uses

4.What variable names are valid

$ name

$ _name

$ 1name

$ name1

$ NAME

$ var-name

$ {"2name"}

5. what will be displayed as a result of this script

$ a = "z";

$ z = "k";

$$ a = "f";

echo $ a. $ z;

6. with the help of which PHP function is the check performed whether the variable was set

7. Define a constant DBNAME with the value 'basename' and output it.

8.What is the result of running this script?

$ a = 1;

$ b = 2;

echo '$ a'. '$ b';

9.What is the result of running this script?

$ a = 3;

$ b = - $ a;

echo "$ a. $ b";

10.What is the result of running this script?

$ name = 'John';

$ surname = 'Smit';

echo $ name + '' + $ surname;

11. How to convert object to string

12.What operator should be used inside a function to initialize a variable that preserves its value between different function calls.

13. What operator should be used inside the function to access the variables external to this function.

14. What is the result of running this script?

function oranges (& $ orages = 17)

{

$ orages. = 1;

}

$ apples = 5;

oranges ($ apples);

echo $ apples;

function oranges ($ orages = 17)

{

$ orages. = 1;

}

$ apples = 5;

oranges ($ apples);

echo $ apples;

15.What is the result of running this script?

$ a = '12345';

$ a [$ a [1]] = "2";

echo $ a;

16 write functions for checking on the existence of such an element of the array

$ a [6] = NULL;

17. write a function to split a string into array elements, for example

the string "1,2,3,4,5" in the array array (1,2,3,4,5);

18. What characters need to be escaped inside a string with double quotes PHP?

19. чем отличаются строка с двойными и одинарными кавычками в PHP?

20 как получить текущую минуту используя PHP?

21 какие функции для работы с файлами вы знаете?

22. как задать значение cookies в PHP которая будет существовать пока сессия не завершится?

23. закие функции для работы с cookies в PHP вы знаете, их назначение?

24. перечислите модификаторы доступа в PHP

25. как выполнить конструктор родительского класса внутри функции (конструктора )?

26.экземпляры какиех классов можно передать этой функции function special (A $class){}?

class A {}

class B {}

class C extends A {}

class D extends B {}

27. какие магические методы в PHP вы знаете? их назначение?

28. имплементируйте класс (классы) для работы следующей цепочки вызовов

echo $manager->getEntity("User")->getName();

29/ какие паттерны программирования вы знаете? какое их назначение, привести примеры использования

30 назовите назначение компонентов MVC

31 что появилось в PHP 5.3+?PHP 5.6+?или что появилось в PHP 5 по сравнению с PHP 4?

32. с камими PHP фреймворками вам приходилось работать?

33. напишите регулярное выражение для проверки емейла?

Вопрос : Расскажите о замыканиях в PHP. Приведите примеры, когда, почему и как они могут быть использованы?


Замыкания полезны в тех ситуациях, когда некоторая часть логики должна выполняться в ограниченном контексте, но при этом должна сохранить возможность взаимодействия с окружающей средой, внешней по отношению к этому контексту.

Первый строительный блок для замыкания – это анонимные (лямбда) функции, т.е. такие функции, у которых нет ассоциированных с ними имён. For example:

// 2nd argument for array_walk is an anonymous function
array_walk ($ array, function ($ dog) {
    echo $ dog-> bark ();
 }); 


Although anonymous functions do not have a name associated with them, they can be associated with variables or passed as a callback parameter to a higher order function. Example:

// declare an anonymous function and associate it
// with $ dogs_bark variable
$ dogs_bark = function ($ dog) {  
    echo $ dog-> bark ();
 }
array_walk ($ array, $ dogs_bark);


The internal structure of closures in PHP is represented by a special class of closures - Closure.
The content of an anonymous function exists in its scope regardless of the scope in which the function was created. However, you can explicitly associate one or more variables from the external scope, which can be referenced in the scope of an anonymous function. To do this, use the use construct when defining an anonymous function.

Sample code

class Dog {
    public function bark () {echo 'woof';  }
 }

$ dogs_bark = function ($ dog) use (& $ collar) {// link by link
    if ($ collar == 'fitsWell') {
         echo $ dog-> bark (); // 'woof'
     } else {
         echo 'no bark'; // collar ($ collar) is too tight
     }
 };

$ dog = new Dog;

$ collar = 'fitsWell'; // external variable
$ dogs_bark ($ dog); // 'woof'

$ collar = 'tight';
$ dogs_bark ($ dog); // 'no bark'


The ability to access external variables within a closure is especially useful when using higher order functions. Take, for example, the function array_walk ($ array, $ calback), which, like other similar functions, allows you to bypass the set of variables passed to it and process them in a specific way. This function bypasses the $ array array and at each iteration calls an anonymous function ($ callback), passing to it only the value of the current element and its key. Therefore, using the $ collar variable without a closure and the use construction will fail. Of course, we can use the global keyword, but this will lead to the senseless cluttering of the global variable namespace, which is needed only in this particular context.
Closures have additional object-oriented features. Starting with PHP 5.4, new methods have appeared in the interface of the Closure class: bind () and bindTo (), which can be used to bind new objects to the closure. For example:

 Closure :: bindTo ($ newthis, $ newscope); 


This method duplicates a closure and associates its scope with a new object in such a way that inside the closure the $ this variable will become a reference to $ newthis in the object context. Let's change the $ dogs_bark function to use the $ this variable, and then bind it to the $ dog object.

 // declare the closure, but do not associate it with the object
 $ dogs_bark = function () {
     echo $ this-> sound;  // where sound is a property of the $ this object
 };
 $ new_dog = new Dog ();
 // create a new closure and bind it to the $ new_dog object
 $ new_closure = $ dogs_bark-> bindTo ($ new_dog);
 $ new_closure ();  // displays the value of the $ sound property


Binding a closure to a variable and accessing $ this is a fairly powerful feature. In particular, we can assign a closure to a property of an object, essentially turning it into a method of this object.

 $ dog = new Dog ();
 $ dog-> closure = $ dogs_bark;
 $ dog-> closure ();


As a result, we can change the behavior of an object at run time without the need to redefine the class signature. This feature is useful in those situations when the functionality needs to be improved, but the code cannot be changed, or the change is necessary in a limited context.
To the list of questions

Question: Explain for what purpose and how the global keyword is used. Give an example of when its use is appropriate and when not.


In the past, PHP's object-oriented features were much simpler than they are now, and therefore you can often find outdated code that actively uses the global keyword. In many respects, using global variables is a spit in the face of all the best practices of object-oriented programming. It leads to the emergence of excessive interdependence between classes, complicates the separation of logic, leads to pollution of the global namespace by variables that are used in one particular context and are not needed in others.

Consider a simple example:

 class Dog {
     function bark () {
         global $ sounds;
         return $ sounds-> bark ();
     }
 } 


The code demonstrates the emergence of the hidden dependency of the Dog class on the $ sounds global variable. Of course, there are cases when this is justified (suppose there is a single set of sounds in the system that never changes at all), but it is much better to explicitly transfer $ sounds to the object of the Dog class in the constructor, and store and use it within this instance:

Code example

 class Dog {
     protected $ sounds; 
     function __construct ($ sounds) {
         $ this-> sounds = $ sounds;
     }

     public function bark () {
         return $ this-> getSounds () -> bark ();
     }

     public function getSounds () {
         return $ this-> sounds;
     }
 }


But, as often happens in programming, never say never. There are a number of reliable and stable products written in PHP that actively use global variables: Wordpress, which runs about 20% of all sites (and this number grows from year to year), Joomla! 1.5 (yes, it is still widely distributed) and the iLance Enterprise Auction system are all examples of successful projects that have used global variables for many years. Similarly, you may have situations in which global variables will be relevant, but you should be careful when using them.
To the list of questions

Q : Tell us about the namespaces in PHP and why they are useful.


One of the object-oriented innovations in PHP 5.3 is the namespace. As the name implies, the namespace defines such a scope in a program, within which the names of classes, interfaces, functions, variables and constants will not cause conflicts with elements that have the same names in another namespace.

Before PHP 5.3, classes were often given long names to reflect the structure of packages in their names and to avoid name conflicts. Suppose we have a class Dog, defined in the application model Dog_Pound. Without a namespace, the full class name would look like this:

 class Dog_Pound_Model_Dogs {// oh, try it out
     function getDogs ();
 }


The explicit assignment of a namespace, in the scope of which all elements (classes, variables, etc.) will be defined, allows the developer to solve this problem. When using the namespace, the above verbose class name can be replaced by the following:

 namespace dog_pound \ model;  // specify the current namespace
 class Dogs {// declare only "Dogs" in dog_pound \ model
     function getDogs ();
 }
 $ dogs = new Dogs;  // class of the object being created is uniquely defined
 // because  in the current namespace, he alone has that name


Relative references to namespaces are also supported. For example, when you are in the dog_pound space, you can create an instance of the Dogs class like this:

 $ dogs = new model \ Dogs // only one "model" is defined in dog_pound


In addition, elements from one namespace can be imported to another and used directly in it (that is, without references to the original namespace). This can be achieved using the use keyword:

 namespace this \ new \ namespace;  // current namespace

 // import Dogs from the dog_pound \ model space
 use dog_pound \ model \ Dogs;

 $ dogs = new Dogs;


To the list of questions

Question : What are traits, traits? Describe their main characteristics and tell them how useful they are. Give an example of the declaration of a type and a class that uses several types.


Types are a great addition that appeared in PHP 5.4, allowing you to add behavior to a class without the need to extend the parent class through inheritance (up to version 5.4, this could be done using an impurity pattern). It is important to note that in the context of a single class, you can use several types. Their use helps to improve the organization of the code and the separation of duties, and also complies with the well-known design principle, which says: “prefer composition to inheritance”.

A couple of examples of typecasting:

 trait Movement {
     public function topSpeed ​​() {
         $ this-> speed = 100;
         echo "Running at 100%!"  .  PHP_EOL;
     }
     public function stop () {
         $ this-> speed = 0;
         echo "Stopped moving!"  .  PHP_EOL;
     }
 }

 trait Speak {
     public function makeSound () {
         echo $ this-> sound.  PHP_EOL; 
     }
 }


Now we use the use keyword, but not to import the namespace, but to include types in the class definition:

Code example

 class Dog {
     use Movement, Speak;  // now the class Dog has a functional of these types
     protected $ sound;
    
     function __construct () {
         $ this-> sound = 'bark';
     }
 }

 $ dog = new Dog ();
 $ dog-> topSpeed ​​();  // from type Movement
 $ dog-> stop ();  // from type Movement
 $ dog-> makeSound ();  // from speak type


To the list of questions

PHP on the fingers


Memorizing things that can be easily found in a language specification or API documentation is not an indication of mastery. Nevertheless, everyone who is intimately familiar with the language knows its syntactic and functional features and nuances on the fingers. Here are some questions that allow you to evaluate the candidate from this side.

Question : Tell us how php: // input and $ _POST are interconnected and how to get access to the php: // input stream?


In simple terms, $ _POST is a superglobal array representing the analyzed and formatted request body sent to the server by the post method.

Sample Query Text

 POST /php-hiring-guide/php-post.php HTTP / 1.1
 Host: toptal.com
 Referer: http: ///toptal.php/php-hiring-guide/php.php
 Content-Type: application / x-www-form-urlencoded
 Content-Length: 63
 article_name = PHP Hiring Guide & tag_line = You are hired! & action = Submit


Access to the request body can be obtained through the input stream in the same way as any files are read:

 $ input = file_get_contents ("php: // input"); 


To the list of questions

Question : Name at least five superglobal variables whose names begin with $ _, and give them a definition. Tell about their relationship with the $ GLOBALS variable.

List of superglobal variables

$ _POST is an associative array containing key-value pairs sent to the server by the post method.
$ _GET is an associative array containing key-value pairs sent to the server using the get method.
$ _REQUEST - the union of key-value pairs from $ _POST and $ _GET.
$ _SERVER - represents the web server parameters related to program execution.
$ _ENV - contains values ​​associated with the server (host) and its configuration.
$ _SESSION is an associative array that stores the values ​​of session variables between page transitions and application launches.
$ _COOKIE - provides access to variables stored in cookies on the client.
$ _FILES is a special array for input data received when sending files to the server using the post method.


The $ GLOBALS superglobal variable is a relative of the global keyword. The $ GLOBALS array stores all variables available in the global scope, including superglobal arrays. For example, access to $ _ENV can be accessed like this: $ GLOBALS ['_ ENV'];
To the list of questions

Question : Explain the purpose and application of the magic methods __get, __set, __isset, __unset, __call, and __callStatic. When, how and why should they be used (or not used)?


The first four methods in our list are used to overload object properties. They allow you to determine how the outside world will interact with the properties declared with the visibility modifier private or protected, or completely absent from the object.

Code example

 // the 'whiskers' property is not declared in the Dog class,
 // but processed by the __get method:
 function __get ($ name) {
     if ($ name == 'whiskers') {
         // create a single whiskersService for the instance
         if (! isset ($ this-> whiskersService)) {
             $ this-> whiskersService = new Whiskers ($ this);          
         }
         // when accessing 'whiskers', whiskersService will be loaded
         return $ this-> whiskersService-> load ();
     }
 }


Now you can simply access the 'whiskers' property:

 $ hairs = $ dog-> whiskers;



Using the __get method to intercept links to properties that look like public ones, we are able to hide implementation details of these properties.
The __set method is applied in the same way:

Code example

 function __set ($ name, $ value) {
     if ($ name == 'whiskers') {
         if ($ value instanceOf Whisker) {
             $ this-> whiskersService-> setData ($ value);
             return $ this-> whiskersService-> getData ();
         } else {
             throw new WhiskerException ("That's not a whisker");
             return false;
         }
     }       
 }


Changing the value of the 'whiskers' property will look like this:

 $ dog-> whiskers = $ hairs; 


This expression will automatically call the __set () method with passing the property name ('whiskers') as the first parameter and the right side of the assignment operator as the second.

Finally, __isset and __unset complete a quartet of methods for overloading properties. Each of them takes only one parameter - the name of the property, and is called when performing the isset () and unset () operations on this property.

Code example

 function __isset ($ name) {
     if ($ name == 'whiskers') {
         return (bool) is_object ($ this-> whiskersService) &&
                                 ! empty ($ this-> whiskersService-> getData ());
     }
 }
 function __unset ($ name) {
     if ($ name == 'whiskers' && is_object ($ this-> whiskersService)) {
         // we do not want to completely stop the service
         $ this-> whiskersService-> reset ();
     }
 }


The two remaining methods, __call and __callStatic, perform a similar function, allowing you to implement method overloading. They allow us to determine how a class and its instances respond to attempts to invoke undefined, protected, or private methods.

Note translator: __call is called when a member is accessed in the context of an object, and __callStatic is called when a static member is accessed. As arguments, they both take the name $ name of the method being called and the $ args array with the parameters passed to the $ name method.

For example, this implementation of __call will lead to the fact that when accessing any "invisible" method, the whiskersService will be loaded:

 public function __call ($ method, $ args) {
     return $ this-> whiskersService-> load ();
 }


The __callStatic method works in the same way and takes the same arguments, but it is called when accessing the “invisible” method not in the context of an object, but in a static context. If we define this method, we will be able to handle calls like ClassName :: notVisibleMethod ().

 public function __callStatic ($ method, $ args) {
     if (! is_object (static :: $ whiskersService)) {
         static :: $ whiskersService = new Whiskers (__ CLASS__);
     }
     return static :: $ whiskersService-> load (); 
 }

 $ hairs = Dog :: whiskers ();


In the examples above, we encapsulated the implementation of whiskers from the outside world, making it the only object available in this way. Clients of the methods and properties defined by us do not know anything about the base class of those whoskersservice and how Dog stores its data in general.

Taken together, these methods improve the possibilities for flexible composition. The degree of abstraction of objects, encapsulation, code compactness (and, as a result, system controllability) also increases.

Using magic methods, it should be remembered that the benefits obtained come at a price. First, these methods are performed more slowly than accessing explicitly defined public properties, as well as slower installers and recipients. Secondly, they prevent the use of many useful tools, such as reflection, autocompletion in IDE, utilities of automatic documentation (for example, PHPDoc). If these things matter, then it may be worth defining public methods and properties explicitly. As in many other cases, the question of whether to use magic methods cannot be answered unambiguously. Strengths and weaknesses must be assessed in each case.
To the list of questions

Question : Describe several data structures from the PHP Standard Library (SPL). Give examples of use.


The PHP development process is mostly related to receiving and processing data from various sources, such as databases, local files, remote APIs, etc. Developers spend a lot of time organizing data, getting it, moving and processing it. The most commonly used structure for representing data in PHP is an array. However, in some cases, arrays are not suitable for solving problems due to insufficient performance and excessive memory consumption, and therefore more suitable data structures are required.

Given how often they talk a lot about frameworks, finding a developer with serious development experience with a framework from your project becomes a daunting task. Ultimately, the activity of the developer community leads to a decrease in the number of programmers working with one particular framework and redistribution in favor of others. Because of this, it is quite difficult to find a developer with the necessary skills.

The use of the standard PHP library (Standard PHP Library, SPL) and knowledge of its composition is an area whose possession can confirm the competence of a PHP developer. If a candidate has a decent experience with SPL, then most likely he will be able to successfully work on your application, regardless of the frameworks used in your environment.

Including the candidate must know the data structures provided in the PHP documentation. Many of them have similar functionality, but small differences allow them to be used in specific situations.

List of SPL data structures with brief explanations

SplDoublyLinkedList is a doubly linked list. Each node of such a list stores a link to the previous one and to the next node. Imagine that you are in line at the bank and at the same time can only see the person in front of you and behind you. This is the analogy of the relationship between the elements in SplDoublyLinkedList. Inserting an item into the list corresponds to the situation when someone got into the queue, and you suddenly forgot who was standing in front of you (and that someone forgot about you). A doubly linked list allows you to efficiently bypass and add large data sets without the need for re-hashing.

SplQueue and SplStack are very similar to SplDoublyLinkedList. Both of these structures, in fact, are doubly linked lists with different iterator flags (IT_MODE_LIFO - Last In First Out - last came, first left; and IT_MODE_FIFO - First First First Out - first came, first left) that regulate the order of processing nodes and what do with these items after they are processed. Another difference between these structures is that the SplQueue interface contains more intuitive methods enqueue () and dequeue (), unlike the push () and pop () methods of SplStack.

SplHeap is a heap represented as a binary tree, each node of which has no more than two child nodes. This is an abstract class that requires an extension with the definition of a compare () method, which allows real-time sorting when inserting new nodes into the tree.

SplMaxHeap and SplMinHeap are concrete implementations of the abstract SplHeap class. SplMaxHeap implements the compare () method so that the tree is sorted in decreasing order of node values, and SplMinHeap in ascending order of values.

SplPriorityQueue is a queue similar to SplHeap, but unlike SplHeap, sorting is based on the value of the priority property (priority) set for each node.

SplFixedArray is a fixed-length array whose index can only be integers. These constraints provide a faster array processing speed, which is achieved, in part, due to the fact that SlipixedArray has no hashing of the keys of the elements when they are added (as opposed to regular arrays).

SplObjectStorage is a repository of objects, provides an interface for matching objects to data, or can be used as a container for multiple objects. Allows you to use an object as a key for an associative array and associate it with some data.


Also on the data structures of the SPL can be read in Habré.
To the list of questions

Question : What will be equal to $ x after executing the expression $ x = 3 + "15%" + "$ 25"?


Правильный ответ – 18. Давайте разберёмся почему.

PHP поддерживает автоматическое приведение типов, основанное на контексте, в котором используется переменная.

При выполнении арифметических операций над выражением, содержащим строку, эта строка будет интерпретирована как число, что позволяет выполнить вычисление выражения. Если строка начинается с одной или нескольких цифр, то все остальные символы будут проигнорированы, а цифры будут представлены в виде числа соответствующего числового типа. С другой стороны, если строка начинается не с цифры, то в контексте арифметического выражения она будет интерпретирована как нуль.

Зная это, мы можем увидеть, что в выражении $x = 3 + "15%" + "$25" строка "15%" будет соответствовать числу 15, а строка "$25" — нулю. Поэтому результат выражения будет равен 18 (3 + 15 + 0).

Одни программисты считают автоматическое приведение типов ценной особенностью, другие – отвратительным недостатком PHP. С одной стороны, осознанное и правильное его применение добавляет удобства разработчику (нет необходимости писать код для конвертации «15» в 15 перед применением арифметической операции). С другой стороны, оно может легко привести к трудноулавливаемым ошибкам, если будет задействовано случайно (т.к. не будет выдано никаких предупреждений и ошибок).
К списку вопросов

Вопрос : Объясните назначение ключевого слова static при вызове метода или обращении к свойству. Расскажите, когда и зачем его нужно использовать, а также чем оно отличается от ключевого слова self. Приведите пример.


В PHP, начиная с версии 5.3, реализовано позднее статическое связывание. Термин «позднее связывание» означает, что ключевое слово static связывает метод или свойство (к которому происходит обращение через static::) не с тем классом, в котором был определён использующий его метод, а с тем, в котором этот метод был вызван во время выполнения. Кстати, название «статическое связывание» не совсем корректно, т.к. static допустимо использовать не только для обращения к статическим членам класса.

Пример кода

class Dog {
    static $whoami = 'собака';
    static $sound = 'лает';

    function makeSounds() {
        echo self::makeSound() . ', ';
        echo static::makeSound() . PHP_EOL;
     }

    function makeSound() {
        echo static::$whoami . ' ' . static::$sound;
     }
 }
Dog::makeSounds();



Результат выполнения этого кода не удивляет: «собака лает, собака лает».
Расширим пример:

class Puppy extends Dog {
    static $whoami = 'щенок';
    static $sound = 'гавкает';

    function makeSound(){
        echo static::$whoami . ' скулит';
     }
 }

Puppy::makeSounds();


Вы можете удивиться, но результат выполнения этого кода: «щенок гавкает, щенок скулит». Чтобы понять, почему это происходит, давайте снова посмотрим на метод makeSounds() в классе Dog.

В методе makeSounds() сначала вызывается self::makeSound(). self:: всегда указывает на контекст того класса, в котором происходит обращение через него (в данном случае это класс Dog). Поэтому self::makeSound() всегда будет приводить к версии метода makeSound() из класса Dog. Это справедливо и в том случае, когда происходит вызовPuppy::makeSounds(), т.к. в классе Puppy нет собственного метода makeSounds(), и поэтому вызывается методmakeSounds() из класса Dog. В результате, при вызове Puppy::makeSounds() выполняется self::makeSound(), что приводит к появлению текста «щенок гавкает».

Затем в методе makeSounds() класса Dog вызывается static::makeSound(). static:: обрабатывается иначе, чем self::. При обращении через static:: используется версия метода, определённая в контексте вызвавшего этот метод класса во время выполнения (в данном случае, это класс Puppy). Следовательно, вызов static::makeSound() приводит к выполнению версии метода makeSound() из класса Puppy. Именно по этой причине при вызове из Puppy::makeSounds()метода static::makeSound() выводится текст «щенок скулит».


К списку вопросов

Под капотом PHP


Понимание того, как PHP работает «под капотом» – одна из важнейших характеристик, определяющих эксперта по PHP. Такой кандидат не только знает, как реализовать какую-то возможность, но также знает несколько возможных решений, их различия по функциональности и производительности.

Вопрос : Расскажите о внутреннем устройстве массивов в PHP?


продолжение следует...

Продолжение:


Часть 1 PHP Interview Questions and Answers
Часть 2 Conclusion - PHP Interview Questions and Answers


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)