This interview guide is for educational and informational purposes only. It is designed to help readers prepare, but it does not guarantee any interview result, hiring decision, offer, or outcome. Interview questions, hiring criteria, and preferred answers can vary by employer, interviewer, industry, location, and time. The examples and explanations reflect the authors' research and judgment, are provided without warranties of any kind, and should not be treated as the only correct approach. Diagrams are simplified illustrations intended to highlight the main components and their interactions; actual systems and implementations may be more complex. Alternative approaches may be equally valid or better suited to a particular question, context, or interviewer. To the fullest extent permitted by applicable law, the author, contributors, and publisher are not liable for decisions made, actions taken, or losses incurred based on this guide.
Identity, Image, and Privacy Notice
To respect individual privacy, some names, profile photographs, avatars, biographical details, and other identifying information displayed in this guide may be replaced with pseudonyms, licensed stock images, illustrative avatars, composite images, or representative descriptions. Unless a person is expressly identified as an actual contributor, a displayed name, image, or profile should not be understood as depicting or identifying a specific candidate, interviewer, employee, or other real individual. These representations are provided for editorial and illustrative purposes only and do not imply endorsement, employment, participation, or affiliation with this guide or any company mentioned in it. Any resemblance to an actual person is coincidental.
Company Notice
This guide is an independent educational resource and is not affiliated with, endorsed by, sponsored by, or approved by the company named in this guide. Company names are used only to identify interview experiences commonly reported by candidates. Interview practices can change without notice, and inclusion of company-specific content does not mean these questions are official, complete, or guaranteed to be asked. To the fullest extent permitted by law, the author, contributors, and publisher are not responsible for outcomes related to use of this material.
Questions or comments?
Contact us for general questions, or share feedback, technical corrections, and comments with the community.
Define Composer as the standard dependency manager for PHP projects. Explain composer.json, composer.lock, package version constraints, repositories such as Packagist, the vendor directory, install versus update, scripts, and the generated autoloader. Distinguish Composer from PHP itself, a system package manager, and a web framework.
Short Interview Answer (30-60 seconds)
Composer is the standard dependency manager for PHP projects. I declare the packages my project needs in composer.json, and Composer resolves compatible versions and normally installs them in the vendor directory. composer.lock records the exact resolved versions so the same dependency set can be installed again. I normally use composer install with an existing lock file and composer update when I intentionally want Composer to resolve newer allowed versions. Composer also generates an autoloader that applications can use to load installed classes.
Detailed Explanation
Composer helps a PHP project use reusable software from other developers in a controlled way. Instead of finding files by hand, copying them into a project, and remembering which copies were used, you describe what the project needs. Composer finds suitable versions, downloads them, and records the choices. This makes it easier for developers, test systems, and production systems to use the same software. It also puts downloaded packages in one normal location and prepares loading information so the application can use their classes without manually including every file.
Useful Questions to Ask the Interviewer
Would you like me to explain the difference between composer install and composer update?
Should I also explain composer.json, composer.lock, Packagist, and the generated autoloader?
How to Explain It in an Interview
Composer is the standard dependency manager for PHP projects. It is a separate command line tool. It is not PHP itself, an operating system package manager, or a web framework.
composer.json describes the packages a project requires. It can also contain version constraints that tell Composer which package versions are acceptable. Composer resolves a set of versions that satisfies those constraints and the requirements of the packages involved.
Packagist is the default public package repository used by Composer. A project can also configure other repositories when needed.
Composer normally installs downloaded packages in the vendor directory. It also generates vendor/autoload.php. An application can require that file so classes from installed packages can be loaded automatically. Packages often provide loading rules such as PSR 4 mappings, and Composer uses those rules when generating its autoloader.
composer.lock records the exact versions Composer resolved. When a lock file exists, composer install installs those locked versions. If there is no lock file, composer install resolves dependencies from composer.json and creates a lock file. This distinction is important because a committed lock file helps development, testing, and production use the same dependency versions.
composer update resolves versions again within the constraints in composer.json and updates composer.lock. It can update all dependencies or selected packages. Updates should therefore be intentional and tested.
Composer can also run scripts attached to supported Composer events. Because such scripts can execute commands or PHP callbacks, projects should use trusted packages and review dependency changes carefully.
Where it is used
Composer is used in modern PHP applications that depend on reusable libraries, development tools, or frameworks. Teams commonly use it during local development, automated testing, build processes, and production deployment. A project may use Composer to install an HTTP client, a logging library, a testing tool, or framework packages. Applications normally commit composer.lock so tested dependency versions can be installed consistently in other environments. The generated autoloader also gives the application one standard entry point for loading classes provided by installed packages.
Why Interviewers Ask This
Interviewers ask this to check whether the candidate understands how PHP projects manage external packages in real applications. They want to see whether the candidate knows the purpose of composer.json, composer.lock, version constraints, repositories, the vendor directory, scripts, and automatic class loading. They also want to confirm that the candidate understands the important difference between installing locked dependencies and intentionally resolving newer allowed versions.
Common interview mistakes
A common mistake is saying Composer is part of PHP. Composer is a separate dependency management tool. Another mistake is calling Composer a web framework or treating it as the same kind of tool as an operating system package manager. Developers also sometimes treat composer install and composer update as identical. With an existing lock file, install uses the versions recorded there. update resolves package versions again within the constraints in composer.json and changes the lock file. Another mistake is assuming install always requires a lock file. If no lock file exists, install resolves dependencies and creates one. Developers should also avoid editing files inside vendor because Composer can replace those files during later installs or updates.
Interview tip
Start by saying that Composer is the standard dependency manager for PHP projects. Then explain composer.json, composer.lock, Packagist, vendor, install, update, and the generated autoloader. Clearly state that install normally reproduces locked versions while update intentionally performs dependency resolution again. Finish by saying that Composer is separate from PHP itself and is not a web framework.
Interviewer may ask next
What happens when you run composer install if composer.lock does not exist?
Composer resolves dependency versions from the constraints in composer.json, installs the resolved packages, and creates composer.lock. This is different from running composer install when a lock file already exists, because an existing lock file tells Composer which exact resolved versions to install. The distinction matters because the first resolution can select any versions allowed by the current constraints, while later locked installs can reproduce that selected dependency set.
Why should a production deployment normally use composer install instead of composer update?
A production deployment should normally use composer install with the committed composer.lock file because it installs the dependency versions that were already resolved and tested. composer update performs dependency resolution again and can select newer versions that still satisfy composer.json. That may introduce changes that were not tested with the application. The tradeoff is that dependency updates must be performed separately and intentionally, but this gives the deployment process much better repeatability and control.
12. What is PSR-4 autoloading?NEWLanguage SpecificEasy
i Question Details
Define PSR-4 as a PHP-FIG specification that maps namespace prefixes to base directories so class names can be resolved to PHP files. Explain the namespace-to-directory and class-to-file mapping, case sensitivity, Composer autoload configuration, vendor/autoload.php, dump-autoload, and the difference between namespaces and autoloading.
Short Interview Answer (30-60 seconds)
PSR 4 is a PHP FIG specification for mapping namespace prefixes to base directories so an autoloader can find PHP class files. For example, if App\ maps to src/, then App\Service\PaymentService maps to src/Service/PaymentService.php. Composer commonly generates this autoloader, and the application usually includes vendor/autoload.php once during startup.
Detailed Explanation
PSR 4 gives a PHP project a predictable rule for finding the file that contains a class. Instead of manually loading every class file, the project connects the beginning of a class name to a starting folder. The remaining parts of the name point to folders inside that starting folder. The final class name points to a PHP file. Composer can prepare this setup for the application. This makes larger projects easier to organize because class names and file locations follow one consistent rule. Namespaces provide names for classes, while autoloading provides a way to find their files.
Useful Questions to Ask the Interviewer
Would you like a Composer configuration example?
Should I also explain the difference between namespaces and autoloading?
How to Explain It in an Interview
PSR 4 is a specification from PHP FIG. It defines how a fully qualified class name can be resolved to a PHP file by an autoloader.
For example, suppose the namespace prefix App\ maps to the base directory src/. The class App\Service\PaymentService maps to src/Service/PaymentService.php. The configured namespace prefix is removed first. Each remaining namespace separator represents a directory boundary. The final class name becomes the file name with the .php extension.
Case matters. The namespace parts and class name used for the mapping must match the case of the corresponding directories and file name. This is especially important when code moves between file systems that handle case differently.
Composer is the common tool used to configure and generate PSR 4 autoloading. In composer.json, the autoload section can map a prefix such as App\ to src/. After changing the autoload configuration, run the Composer command composer dumpautoload to regenerate the autoload files. Composer also regenerates them during relevant install and update operations.
The application normally includes vendor/autoload.php once during startup. That file registers Composer's autoloader with PHP. When PHP encounters a class that is not already loaded, registered autoloaders can be called. Composer then uses its generated mapping information to locate and include the matching file.
Namespaces and autoloading solve different problems. A namespace gives a class its qualified name and prevents many naming conflicts. Autoloading controls how the file containing that class is found and loaded. Declaring a namespace by itself does not load a file.
Where it is used
PSR 4 is commonly used in Composer based PHP applications and reusable packages. It is useful when source code contains many classes under directories such as src/ and tests/. Production applications commonly load vendor/autoload.php during startup so application classes and installed package classes can be loaded when PHP first needs them.
Why Interviewers Ask This
Interviewers ask this to check whether the candidate understands how modern PHP projects organize classes and load class files when they are first needed. It also tests whether the candidate can separate namespaces from autoloading and whether they understand how Composer commonly implements PSR 4 mappings in production projects.
Common interview mistakes
Common mistakes include thinking that declaring a namespace automatically loads its file, placing a class in a directory that does not match the configured mapping, using directory or file name case that does not match the namespace or class name, changing Composer autoload configuration without regenerating the autoload files, and forgetting to include vendor/autoload.php in the application startup path.
Interview tip
Start with the mapping rule. Give one simple example such as App\Service\PaymentService mapping to src/Service/PaymentService.php. Then explain that Composer commonly generates and registers the autoloader. Finish by saying that namespaces name classes, while autoloading finds and loads their files.
Interviewer may ask next
What happens if the case of a class name or file path does not match the PSR 4 mapping?
The case should match exactly. PSR 4 requires the relevant namespace and class portions to match the case of their corresponding directory and file names. A mismatch can appear to work on a file system that ignores case but fail on a case sensitive production system. Consistent case therefore prevents environment specific loading failures.
Why use Composer PSR 4 autoloading instead of manually including every class file?
Composer PSR 4 autoloading is usually easier to maintain in a structured application. Code can refer to qualified class names without keeping a long list of manual file includes. Composer also manages autoload information for installed packages and application classes. The main tradeoff is that namespace mappings, directory structure, and file names must stay consistent, and generated autoload information must be refreshed when its configuration changes.
13. What is a PHP session?NEWLanguage SpecificEasy
i Question Details
Define a PHP session as server-side state associated with a client through a session identifier, commonly carried in a cookie. Explain session_start, the $_SESSION store, session persistence, regeneration, expiration, storage handlers, locking, logout, and security risks such as fixation and hijacking. Distinguish sessions from cookies and stateless authentication.
Short Interview Answer (30-60 seconds)
A PHP session lets the server keep state for the same client across multiple requests. PHP normally links the client to that state through a session identifier, commonly stored in a cookie. I call session_start() before using $_SESSION. For login sessions, I also regenerate the identifier after authentication, use secure cookie settings, apply clear expiration rules, and destroy the session correctly during logout.
Detailed Explanation
A session is a way for a web site to remember information about one visitor while that person moves between pages. For example, after a person signs in, the site can remember that person instead of asking for a password on every page. The important point is that the main information is kept by the web site. The visitor's browser normally carries only a small identifier. The web site uses that identifier to find the correct saved information when the visitor sends another request.
Useful Questions to Ask the Interviewer
Should I explain the default PHP session behavior as well as custom session storage?
Should I include security practices for login sessions?
How to Explain It in an Interview
A PHP session is server side state associated with a client through a session identifier. The identifier is commonly carried in a cookie named PHPSESSID, although PHP configuration can change the cookie name and transport behavior.
Calling session_start() starts a new session or resumes an existing one. PHP obtains the session identifier, uses the configured session handler to load the matching data, and makes that data available through the $_SESSION array. Values stored in $_SESSION can therefore persist across separate HTTP requests while the session remains available.
The session data is stored through a session save handler. The default files handler stores session data in files. Applications can configure another supported handler or provide a custom handler when they need a different storage system.
A session is different from a cookie. A cookie stores its own value on the client. With a normal PHP session, the important application state is stored on the server and the client usually carries only the session identifier. A session is also different from stateless authentication. Stateless authentication does not require the server to load stored session state for every authenticated request.
Security is important because a stolen valid session identifier can allow an attacker to use the victim's session. After authentication or another privilege change, the application should normally regenerate the session identifier with session_regenerate_id(). Secure session cookies should normally use Secure on HTTPS sites, HttpOnly, and an appropriate SameSite setting. Enabling strict session identifier handling can also reduce acceptance of uninitialized identifiers.
Expiration needs application care. Cookie lifetime and server side session data lifetime are separate concerns, and automatic cleanup does not provide an exact security timeout. Sensitive applications should enforce their own idle or absolute timeout rules.
During logout, removing values from $_SESSION alone is not enough for a complete logout. The application should clear authentication state, remove the session cookie when appropriate, and destroy the server side session.
Session locking also matters. With the default files handler, PHP normally locks the session data while the session is open. Concurrent requests using the same session can therefore wait for each other. If code no longer needs to change session data, session_write_close() can save and close the session earlier.
Where it is used
PHP sessions are commonly used for signed in user state, shopping carts, short lived form progress, access control information, and other values that must remain available across several requests. In production systems with several PHP workers or several application servers, the deployment must ensure that requests which need a session can reach the required session data. This may require shared session storage or another deployment strategy that keeps session access consistent.
Why Interviewers Ask This
Interviewers ask this to check whether the candidate understands how PHP keeps user state across separate requests. They also want to see whether the candidate understands session identifiers, session storage, expiration, locking, logout behavior, and security risks such as session fixation and session hijacking.
Common interview mistakes
Common mistakes include thinking the complete session is stored in the browser, forgetting to call session_start() before using $_SESSION, treating the session identifier as harmless data, failing to regenerate the identifier after authentication, assuming session cleanup gives an exact security timeout, forgetting that destroying server side session data does not automatically remove the browser cookie, and leaving a session open longer than necessary when session locking delays concurrent requests.
Interview tip
Start by saying that a PHP session keeps server side state across requests and links that state to a client through a session identifier. Then explain session_start(), $_SESSION, storage, persistence, regeneration, expiration, locking, logout, and the difference between sessions, cookies, and stateless authentication.
Interviewer may ask next
What can happen when two requests from the same PHP session run at the same time?
They can block each other when the active session handler uses locking. With the default files handler, session_start() normally locks the session data, so another request for the same session can wait until the first request closes the session or finishes. This matters for pages that send several requests at once. If the first request no longer needs to change session data, calling session_write_close() releases the session earlier and lets another request continue.
When would you choose a PHP session instead of stateless authentication?
I would choose a PHP session when the application benefits from keeping authentication or other client state on the server and can manage the required session storage. Server side sessions make centralized revocation and state changes straightforward because the application controls the stored session. Stateless authentication avoids loading server side session state for every authenticated request, which can simplify some distributed designs. The tradeoff is that sessions require storage, expiration management, and careful protection of the session identifier.
14. What is PHP-FPM?NEWLanguage SpecificEasy
i Question Details
Define PHP-FPM as the FastCGI Process Manager used to run PHP behind a web server such as Nginx or Apache. Explain the request path, master and worker processes, pools, process-management modes, worker limits, timeouts, slow logs, graceful reloads, and how pool sizing affects memory use, concurrency, queueing, and availability.
Short Interview Answer (30-60 seconds)
PHP FPM is the FastCGI Process Manager commonly used to run PHP behind a web server such as Nginx or Apache. The web server sends PHP work to an FPM pool, and an available worker process runs the request and returns the result. The main production concern is worker sizing. Too few workers can make requests wait, while too many workers can consume too much memory and reduce availability.
Detailed Explanation
PHP FPM is a service that manages PHP workers for a web site. A web server receives a visitor request and sends PHP work to this service. The service keeps separate worker processes available. Each worker handles one request at a time. This allows several requests to run at the same time through different workers. The worker count needs careful sizing. Too few workers can make requests wait. Too many workers can use too much memory and make the server unstable. FPM also provides settings for slow requests, long requests, and safe process management.
Useful Questions to Ask the Interviewer
Are you asking about a typical Nginx or Apache setup?
Should I also explain how to size and monitor an FPM pool?
How to Explain It in an Interview
PHP FPM means FastCGI Process Manager. It is a PHP server interface designed to manage FastCGI processes. A common request path is browser to Nginx or Apache, then through FastCGI to an FPM pool. An available FPM worker executes the PHP script and returns the response through the web server.
FPM has a master process that manages worker processes. Workers are organized into pools. Each pool can have its own listening address or socket, operating system user, PHP settings, and process limits. Normal requests execute in separate worker processes, so ordinary mutable request state is not shared between workers.
FPM supports three process management modes. Static keeps exactly the configured number of workers. Dynamic adjusts the number of workers while staying within configured limits. Ondemand creates workers when requests arrive and removes workers after they stay idle for the configured time. The pm.max_children setting defines the maximum number of child processes that can serve requests at the same time. ([php.net](https://www.php.net/manual/en/install.fpm.configuration.php?utm_source=chatgpt.com))
Worker sizing is a memory and concurrency tradeoff. More workers allow more requests to execute at once, but each worker uses memory. When all allowed workers are busy, new connections can wait in the listen queue. A very high worker limit can exhaust memory and hurt availability.
FPM also has production controls. request_terminate_timeout can terminate a worker serving a request that exceeds the configured time. request_slowlog_timeout can trigger a PHP stack trace in the configured slowlog for a slow request. pm.max_requests can recycle a child after it has handled a chosen number of requests, which can help contain memory growth in application code or third party libraries. FPM also supports graceful reload behavior so configuration can be reloaded while existing work is allowed to finish rather than using an immediate hard stop. ([php.net](https://www.php.net/manual/en/install.fpm.configuration.php?utm_source=chatgpt.com))
Where it is used
PHP FPM is commonly used on production web servers where Nginx or Apache receives HTTP requests and passes PHP execution to FPM. It is useful when a team needs controlled request concurrency, separate application pools, worker limits, slow request diagnosis, request time limits, and controlled process lifecycle management. Separate pools are useful when applications need different operating system users, PHP settings, sockets, or resource limits.
Why Interviewers Ask This
Interviewers ask this question to check whether a candidate understands how PHP commonly runs in production. They want to see knowledge of the request path, FPM processes, pools, worker limits, time limits, slow request diagnosis, reload behavior, memory use, concurrency, queueing, and availability.
Common interview mistakes
A common mistake is saying that Nginx or Apache directly executes the PHP script when the setup actually passes PHP work to FPM. Another mistake is thinking one FPM worker runs several PHP requests at the same instant. A worker normally executes one request at a time. It is also wrong to assume that increasing pm.max_children always improves performance. Too many workers can exhaust memory and reduce availability. Other mistakes include ignoring queued connections, slow request logs, request time limits, worker recycling, and the fact that normal mutable request state is not shared between separate FPM worker processes.
Interview tip
Start with the request path. Explain that the web server passes PHP work through FastCGI to an FPM pool and an available worker executes it. Then explain the master process, pools, static, dynamic, and ondemand modes, and pm.max_children. Finish with the main tradeoff: more workers can increase concurrency, but they also increase memory use, so production sizing must balance memory, queueing, and availability.
Interviewer may ask next
What happens when every allowed PHP FPM worker is busy and another request arrives?
The new request cannot start PHP execution immediately because no worker is free and pm.max_children prevents the pool from creating more than its configured maximum. The connection can wait in the listen queue while it waits for a worker, subject to the configured queue capacity and the surrounding server limits. This matters because queueing increases response time, and sustained overload can eventually cause failed requests. I would not automatically increase the worker limit. I would first check memory per worker, slow requests, CPU use, request duration, queue activity, and available memory before deciding whether more workers are safe.
How would you choose between static, dynamic, and ondemand PHP FPM process management?
I would choose based on traffic patterns, available memory, and how quickly workers need to be ready. Static keeps exactly pm.max_children workers, so its worker count is predictable but idle workers still use memory. Dynamic changes the number of workers according to configured start and spare worker settings while never exceeding pm.max_children. Ondemand creates workers when requests arrive and removes idle workers after pm.process_idle_timeout, which can save memory for low traffic pools but can add process creation cost when new work arrives after an idle period. In all three modes, pm.max_children sets the maximum number of child processes that can serve requests at the same time. ([php.net](https://www.php.net/manual/en/install.fpm.configuration.php?utm_source=chatgpt.com))
15. What is OPcache?NEWLanguage SpecificEasy
i Question Details
Define OPcache as a PHP extension that stores compiled PHP bytecode in shared memory so scripts do not need to be parsed and compiled on every request. Explain the normal request benefit, memory sizing, file-change validation, deployment invalidation or reset, command-line differences, and why OPcache does not cache application data or database results.
Short Interview Answer (30-60 seconds)
OPcache is a PHP extension that stores compiled PHP bytecode in shared memory. PHP can then reuse that prepared code instead of parsing and compiling the same script again for normal web requests. In production, I would enable it, give it enough memory for the application, and make sure deployments correctly activate changed files.
Detailed Explanation
OPcache helps a PHP application respond faster by remembering work that PHP has already done. When PHP runs a program, it first has to read and prepare the program before it can run it. OPcache keeps that prepared form in memory so later requests can reuse it. This saves repeated work when the same PHP files are used many times. It is mainly useful for busy web applications. It does not remember user information, application values, saved page results, or information returned from a database.
Useful Questions to Ask the Interviewer
Are you asking about OPcache for normal web requests or command line scripts?
Should I also explain how deployments make changed PHP files become active?
How to Explain It in an Interview
OPcache is a PHP extension that stores compiled PHP bytecode in shared memory. Bytecode is the prepared form of a PHP script that the PHP engine can execute. PHP can reuse this cached bytecode instead of parsing and compiling the same script again for each normal web request. This reduces repeated work and usually improves application response time and server efficiency. ([php.net](https://www.php.net/manual/en/book.opcache.php?utm_source=chatgpt.com))
The cache has a limited amount of shared memory. The opcache.memory_consumption setting controls its size. Production systems should give it enough memory for the application and monitor cache usage. If capacity is too small, the cache can fill and reduce the performance benefit. ([php.net](https://www.php.net/manual/en/opcache.configuration.php?utm_source=chatgpt.com))
File change validation is also important. With opcache.validate_timestamps enabled, OPcache checks for changed files according to its validation settings. If timestamp validation is disabled, changed source files are not automatically noticed. A deployment must then use invalidation, reset the cache, or restart the appropriate PHP service so new code becomes active. ([php.net](https://www.php.net/manual/en/opcache.configuration.php?utm_source=chatgpt.com))
For command line PHP, OPcache is controlled separately by opcache.enable_cli. Its default setting is off. Short command line programs often gain less because the process ends quickly. ([php.net](https://www.php.net/manual/en/ini.list.php?utm_source=chatgpt.com))
OPcache only caches compiled PHP code. It is not an application data cache and does not cache database query results.
Where it is used
OPcache is commonly used on production PHP web servers where the same application files run across many requests. It is especially useful with PHP FPM because repeated requests can benefit from compiled scripts kept in shared memory. Teams also plan for OPcache during deployments so changed PHP files become active correctly. Command line workloads need separate consideration because OPcache has a separate command line setting.
Why Interviewers Ask This
Interviewers ask this to check whether the candidate understands how PHP prepares scripts for execution and how OPcache improves production performance. They also want to see whether the candidate understands memory sizing, source file validation, deployment behavior, command line differences, and the important limit that OPcache does not store application data or database results.
Common interview mistakes
A common mistake is saying that OPcache caches application data or database results. It does not. It caches compiled PHP bytecode. Another mistake is assuming that edited source files always become active immediately. That depends on file change validation and deployment handling. Candidates may also forget that OPcache uses limited shared memory, so sizing and monitoring matter. Another mistake is assuming command line PHP uses OPcache in exactly the same way as normal web requests. Command line use has its own setting.
Interview tip
Start by saying that OPcache stores compiled PHP bytecode in shared memory so PHP can avoid repeated parsing and compilation. Then explain the production points that matter most: memory sizing, file change validation, deployment invalidation or reset, and command line behavior. Finish by clearly saying that OPcache does not cache application data or database results.
Interviewer may ask next
What happens when PHP source files change while OPcache is enabled?
The result depends on file change validation. When opcache.validate_timestamps is enabled, OPcache checks for changed files according to its validation settings and can compile the changed script again. When timestamp validation is disabled, cached code remains valid until it is explicitly invalidated, the cache is reset, or the appropriate PHP service is restarted. This matters during deployment because the release process must make sure new code becomes active.
Should OPcache always be enabled for command line PHP?
No. Command line OPcache is controlled separately by opcache.enable_cli, and its default setting is off. Long running or repeated command line workloads can benefit in some cases, while short commands may gain little because the process ends quickly. The main tradeoff is whether reusing compiled code provides enough benefit for that workload to justify enabling the cache.
16. What scalar, compound, and special data types does PHP support?Language SpecificEasy
i Question Details
Describe booleans, integers, floats, strings, arrays, objects, callables, iterables, null, and resources, including how type declarations relate to runtime values.
Short Interview Answer (30-60 seconds)
PHP has four scalar types: bool, int, float, and string. Its main compound value types are array and object. Callable describes a value PHP can invoke, while iterable is a type alias for array or Traversable rather than a separate runtime value. Null represents no value, and resource represents a handle managed by PHP or an extension. Type declarations restrict accepted runtime values, but they do not replace or rename the actual type of a value.
Detailed Explanation
PHP can store simple values, collections, created objects, executable values, missing values, and handles to outside systems. These groups help developers choose suitable values and explain what a function accepts or returns. Some names describe actual values that exist while the program runs. Other names are rules that accept one or more kinds of value. Understanding this difference prevents mistakes when validating input, copying data, calling functions, processing collections, and working with files or other external services in a real application.
Useful Questions to Ask the Interviewer
Should I explain both runtime values and declaration only types?
Should I include copying and memory behavior for arrays and objects?
How to Explain It in an Interview
The four scalar types are bool, int, float, and string. A bool is true or false. An int is a whole number within the range supported by the platform. A float uses floating point representation, so some decimal values cannot be stored exactly. A string is a sequence of bytes. Unicode character operations often require the optional mbstring extension.
The main compound value types are array and object. A PHP array is an ordered map with integer or string keys. It can represent a list or lookup structure, but it is not a compact typed vector. Array assignment has value behavior. PHP normally delays the physical copy until one copy is modified, which reduces unnecessary copying, but a changed large array can still require significant memory. An object is an instance of a class. Assigning an object variable copies its object handle, so both variables refer to the same object. The clone keyword creates a new object, and nested object properties remain shared unless they are also cloned.
A callable describes a value PHP can invoke. Examples include a closure, a valid function name, and a valid method callback. Iterable is not a separate runtime value. It is an alias that accepts an array or an object implementing Traversable.
Null is the single value of the null type and means that no value is present. A resource is a special handle created by PHP or an extension for something such as a stream. Resource cannot be used as a user defined type declaration, and many newer APIs use objects instead.
Type declarations can restrict parameters, return values, properties, and class constants where supported. PHP also supports union and intersection declarations, nullable declarations, class types, literal true and false types, mixed, void, and never in their valid positions. A declaration checks the actual runtime value and throws TypeError when the value is not accepted. Strict types changes scalar coercion rules for calls made from the file that enables it, but PHP remains dynamically typed.
Where it is used
Scalar values are used for flags, identifiers, counts, measurements, and text. Arrays are used for configuration, request data, grouped results, and database rows, although dedicated objects can provide clearer contracts for important domain data. Objects model entities, services, value objects, and application behavior. Callables are used for callbacks, sorting rules, event handlers, and middleware. Iterable declarations let a function process either an array or a Traversable object and can support lazy iteration when an iterator or generator is supplied. Null represents an intentionally absent result. Resources appear in stream and extension APIs. Type declarations improve production code by making contracts clearer and causing invalid values to fail earlier.
Why Interviewers Ask This
Interviewers ask this question to check whether the candidate understands the values PHP can hold and the declarations PHP can use to restrict those values. They are also testing whether the candidate can distinguish actual runtime types from aliases and declarations such as iterable, mixed, void, and never. This knowledge helps a developer design clear function contracts, predict conversions, and avoid incorrect assumptions about arrays, objects, callables, null values, and resources.
Common interview mistakes
A common mistake is describing iterable as a separate runtime value. It is an alias for array or Traversable. Another mistake is assuming that callable means every string or array is valid. The value must describe something PHP can actually invoke in the current context. Developers also incorrectly describe a PHP array as a compact list. It is an ordered map and can use much more memory than a compact typed structure. Another mistake is saying normal array assignment permanently shares one mutable array. It has value behavior, although PHP normally delays copying until modification. Object assignment is also often misunderstood. It copies an object handle rather than cloning the object. Other mistakes include using float for exact money calculations, assuming PHP strings automatically understand Unicode characters, declaring resource as a parameter type, and believing strict types disables every automatic conversion in PHP.
Interview tip
Name the four scalar types first. Then explain array and object behavior. Clarify that callable describes an invokable value and iterable accepts array or Traversable. Finish with null, resource, and the key point that declarations validate runtime values rather than creating different runtime values.
Interviewer may ask next
Is iterable an actual runtime value type, and what values satisfy it?
No. Iterable is a type alias that accepts an array or an object implementing Traversable. The actual runtime value remains an array or an object. This matters because each form can have different methods, copying behavior, memory use, and iteration behavior. An iterator or generator can produce values lazily, while an array normally keeps its elements in memory.
What are the main memory and behavior differences between assigning an array and assigning an object?
Array assignment has value behavior, while object assignment copies an object handle. PHP normally uses delayed copying for arrays, so assigning an array does not always duplicate all data immediately. A later modification can cause a separate array structure to be created, which may increase memory use. Assigning an object does not clone it, so changes through either variable affect the same object. Use clone only when an independent object is required, and remember that cloning is shallow unless nested objects are explicitly cloned.
17. Is PHP case-sensitive?Language SpecificEasy
i Question Details
Explain which identifiers are case-sensitive, why relying on case-insensitive behavior is unsafe, and how PSR naming and filesystem case sensitivity affect production code.
Short Interview Answer (30-60 seconds)
PHP is partly case sensitive. Variable names, property names, constant names, named argument names, and string array keys are case sensitive. Function names, method names, and class like names are generally case insensitive at the PHP runtime level. I still use the exact declared case everywhere because PSR 4 autoloading, file names, development tools, and production file systems expect consistent case.
Detailed Explanation
PHP does not use one letter case rule for every name. Some names treat capital and small letters as different. Other names treat them as the same. This means a spelling change may create a different value in one place but still find the same code in another place. The difference can cause confusing errors during development or after deployment. A safe developer therefore writes every name with the same capital and small letters used when that name was first created. This keeps the code clear and prevents avoidable production failures.
Useful Questions to Ask the Interviewer
Should I include Composer and PSR 4 autoloading behavior?
Should I explain differences between development and production file systems?
How to Explain It in an Interview
PHP is partly case sensitive. Variable names are case sensitive. Therefore, $userName and $username are two different variables. Object and static property names are also case sensitive. User defined constant names and class constant names are case sensitive. Named argument names must exactly match the declared parameter names. String array keys are also case sensitive, although array keys are data values rather than PHP identifiers.
Function names and method names are case insensitive for ordinary ASCII letter differences. Class, interface, trait, and enum names are also generally resolved without regard to ASCII letter case after PHP knows the declaration. PHP keywords are case insensitive as well.
This runtime behavior should not be used as a naming strategy. Code that calls UserService as userservice may work when the class is already loaded, but it can fail during autoloading. PSR 4 requires class names to be referenced with the correct case. Namespace directories and class file names must also match the declared case.
The file system adds another production risk. A case insensitive development system may treat UserService.php and userservice.php as the same path. A case sensitive production system treats them as different paths. The application can therefore work locally and fail on a Linux server.
The practical rule is to use the exact declared case everywhere. Consistent case has no meaningful runtime memory cost. Any direct performance difference is negligible. Correct naming mainly improves reliability, portability, readability, static analysis, and autoloading.
Where it is used
These rules matter when declaring and reading variables, accessing object properties, using constants, calling functions and methods, passing named arguments, and reading string array keys. They are especially important in Composer projects that use PSR 4 autoloading. Teams also rely on consistent case during code review, testing, static analysis, deployment, and development across different operating systems.
Why Interviewers Ask This
Interviewers ask this question to check whether the candidate knows that PHP applies different case rules to different names. It tests knowledge of variables, properties, constants, functions, methods, classes, named arguments, and autoloading. It also checks whether the candidate can choose consistent naming that remains safe across development and production systems.
Common interview mistakes
A common mistake is saying that PHP is completely case sensitive or completely case insensitive. Another mistake is assuming that $total and $Total are the same variable. Developers may also forget that property names, constant names, named argument names, and string array keys are case sensitive. A serious production mistake is using the wrong case for a class, namespace directory, or file because the application worked on a case insensitive development system. This can cause PSR 4 autoloading to fail on a case sensitive production system.
Interview tip
Begin by saying that PHP is partly case sensitive. Give one clear example from each group, such as variables being case sensitive and function names being case insensitive. Finish with the production rule that every reference should use the exact declared case, especially for PSR 4 class names and file paths.
Interviewer may ask next
Are named argument names case sensitive in PHP?
Yes, named argument names are case sensitive. The name used in the call must match the declared parameter name exactly. A different letter case does not select that parameter and causes an unknown named parameter error. This matters because changing a public parameter name or its case can break callers that use named arguments.
Why can incorrect class name case work locally but fail in production?
It can happen because the PHP runtime and the file system perform different jobs. PHP generally resolves an already known class name without ASCII case sensitivity, but an autoloader must first map the requested name to a file path. PSR 4 requires matching case, and a case sensitive production file system treats differently cased paths as different files. Exact case prevents this portability and deployment problem.
18. What does the null coalescing operator do in PHP?Language SpecificEasy
i Question Details
Explain the behavior of ?? with undefined and null values, compare it with isset-based logic, and describe chained coalescing.
Short Interview Answer (30-60 seconds)
The null coalescing operator returns the value on its left when that value exists and is not null. Otherwise, it returns the value on its right. It behaves like an isset check followed by a conditional choice. It also preserves valid values such as false, zero, and an empty string.
The null coalescing operator helps PHP choose a backup value. PHP first checks the value on the left. When that value is available and does not contain null, PHP uses it. When the value is missing or contains null, PHP uses the value on the right. This is useful when information may come from a form, a setting, or saved data and the program needs a safe backup. Values such as false, zero, and an empty string are still accepted. They do not cause PHP to choose the backup.
Useful Questions to Ask the Interviewer
Should a missing value and a null value use the same fallback?
Must a present array key containing null be different from a missing key?
Should several possible values be checked in a preferred order?
How to Explain It in an Interview
The operator is written as ??. The expression $value ?? $fallback behaves like isset($value) ? $value : $fallback.
PHP returns the left value when it is defined and not null. If the variable or array key is undefined, or its value is null, PHP evaluates and returns the right expression. Using ?? with a missing variable or array key does not produce the warning that a normal direct read can produce. ([php.net](https://www.php.net/manual/en/language.operators.comparison.php))
For example, $name = $_GET['name'] ?? 'Guest'; keeps the submitted name when it exists and is not null. Otherwise, it uses Guest. False, zero, an empty string, and an empty array remain valid left values.
The operator can be chained. In $language = $requestLanguage ?? $userLanguage ?? $defaultLanguage;, PHP returns the first value that is defined and not null. The operator is right associative, and later fallback expressions are not evaluated after a suitable value is found. ([php.net](https://www.php.net/manual/en/language.operators.precedence.php))
Use ?? when undefined and null should have the same result. Use array_key_exists when a present array key containing null must be distinguished from a missing key. ([php.net](https://www.php.net/array-key-exists))
The operator has low precedence, so parentheses improve correctness when it is mixed with concatenation or arithmetic. It produces a result value rather than a variable, which matters in functions that return by reference. ([php.net](https://www.php.net/manual/en/language.operators.comparison.php))
Its direct runtime and memory overhead is small. It creates no special collection and does not copy a selected value merely because ?? is used. Normal PHP value and copy behavior still applies. Expensive fallback expressions are skipped when the left value is usable.
Example
The example demonstrates the same rules described in the answer. The false value is preserved because it is defined and not null. The null value and the missing array key use their fallback values. The chained expression checks the request value, then the user value, and finally the application default. It returns the first value that is defined and not null.
Code
<?phpdeclare(strict_types=1);
$options = [
'enabled' => false,
'theme' => null,
];
// False is defined and not null, so PHP keeps it.$enabled = $options['enabled'] ?? true;
// Null causes PHP to use the fallback value.$theme = $options['theme'] ?? 'light';
// A missing key also causes PHP to use the fallback value.$language = $options['language'] ?? 'en';
$requestLanguage = null;
$userLanguage = 'fr';
$defaultLanguage = 'en';
// PHP returns the first value that is defined and not null.$selectedLanguage = $requestLanguage ?? $userLanguage ?? $defaultLanguage;
var_dump($enabled);
echo$theme . PHP_EOL;
echo$language . PHP_EOL;
echo$selectedLanguage . PHP_EOL;
Where it is used
It is commonly used to provide defaults for optional form fields, query parameters, decoded data, configuration arrays, environment settings, cache results, and values selected from several sources. It is most suitable when an undefined value and a null value should both trigger the same fallback.
Why Interviewers Ask This
Interviewers ask this question to check whether the candidate understands how PHP handles undefined and null values. It also tests whether the candidate can choose safe fallback values, compare the operator with isset logic, and recognize cases where a missing array key must be distinguished from a key whose value is null.
Common interview mistakes
A common mistake is thinking that ?? rejects every value that PHP can treat as false. It does not. False, zero, an empty string, and an empty array are preserved. Another mistake is using it when null must be distinguished from a missing array key. Both cases select the fallback because the operator follows isset behavior. Developers may also forget its low precedence when combining it with concatenation or arithmetic. Another limitation is assuming its result can be returned as a variable reference.
Interview tip
State the main rule first. Say that PHP returns the left value when it is defined and not null. Then compare it with isset logic, mention that false and zero are preserved, explain chained fallback values, and finish with the array_key_exists distinction.
Interviewer may ask next
What happens if the left value is false, zero, or an empty string?
PHP returns the left value. The null coalescing operator only selects the right expression when the left value is undefined or null. False, zero, and an empty string are defined values, so preserving them matters when they are valid input or configuration choices.
When should array_key_exists be used instead of the null coalescing operator?
Use array_key_exists when a present array key containing null must be distinguished from a missing key. The null coalescing operator follows isset behavior, so both cases select the fallback. array_key_exists gives the required distinction, but it needs more explicit conditional logic.
19. How do include, require, include_once, and require_once differ in PHP?Language SpecificEasy
i Question Details
Compare failure behavior and duplicate inclusion, and explain why Composer autoloading is normally preferred for classes.
Short Interview Answer (30-60 seconds)
The practical differences are failure handling and duplicate evaluation. include raises a warning and returns false if PHP cannot load the file, so execution normally continues. require raises an Error in PHP 8, so code after it does not run unless that Error is caught. include_once and require_once keep the matching failure behavior but skip a file that PHP has already included during the current execution. For classes, I normally prefer Composer autoloading because it loads class files when their classes are needed and avoids manual file lists.
Detailed Explanation
These four PHP statements let one file run code from another file. The main choices are what should happen when the requested file is missing and whether PHP should run a file again after it was already loaded. An optional file may be allowed to fail. A required setup file may not. Running the same file twice can repeat output and other actions, or cause errors when it declares the same class or function again. Composer usually handles class files automatically.
Useful Questions to Ask the Interviewer
Is the file optional or required?
Can several code paths request the same file?
Does the file return data, produce output, or declare classes?
How to Explain It in an Interview
include and require are PHP language constructs that evaluate another file.
If include cannot load the file, PHP raises an E_WARNING warning and returns false. Use it only when the file is optional and the application handles failure safely.
If require cannot load the file, PHP raises an Error in PHP 8. Code after it does not run unless a catch block catches that Error. Use require when continuing without the file would be unsafe.
include_once follows include failure behavior. require_once follows require failure behavior. The once forms also check whether PHP already included the resolved file in the current execution. If so, PHP skips another evaluation and the once expression returns true.
A successful inclusion can return a value from the included file. Without an explicit return, it normally returns 1. Included code inherits the variable scope of the inclusion line. Classes and functions still follow their normal declaration rules.
The once forms add a lookup against PHP records of included files. PHP retains those records for the current execution. The time and memory cost is normally small. OPcache may reduce compilation work, but it does not change inclusion behavior.
For classes, Composer autoloading is normally preferred. The application loads Composer's autoloader once. Composer then resolves a class when PHP needs it, commonly through PSR 4 mappings. This avoids manual class file lists. An optimized class map can reduce file system checks in production.
Where it is used
require is commonly used for a mandatory application bootstrap file or Composer's generated autoloader. require_once can help in procedural or older code when several execution paths may reach the same mandatory declaration file. include is suitable for an optional template or content file only when failure is expected and handled safely. include_once can protect an optional shared file from repeated evaluation. Configuration files that return arrays may also be loaded directly. Application classes, interfaces, traits, and enums are normally loaded through Composer autoloading.
Why Interviewers Ask This
Interviewers ask this question to check whether the candidate understands PHP file inclusion, missing file behavior, duplicate evaluation, return values, and variable scope. It also tests whether the candidate can choose safely between optional and required files and explain why Composer autoloading is normally preferred for classes.
Common interview mistakes
A common mistake is saying that include fails silently. It raises a warning and returns false. Another mistake is saying that require can never be caught. In PHP 8, a failed require raises an Error that implements Throwable, so a matching catch block can catch it. Candidates also assume that once means once for each written path string. PHP checks whether the resolved file was already included during the current execution. Another mistake is assuming that the once forms undo earlier side effects or unload declarations. They only skip another evaluation. Developers should not build inclusion paths from untrusted input because this can create file inclusion vulnerabilities. They should also avoid hiding failures with the at operator. Manually requiring every class file is normally less maintainable than Composer autoloading.
Interview tip
Answer in three parts. First compare missing file behavior. Second explain that the once forms prevent another evaluation of a file already included during the current execution. Third say that Composer autoloading is normally preferred for classes because it resolves class files when needed and removes manual class file lists.
Interviewer may ask next
What happens when require_once is called after the same file was already loaded with include?
PHP skips another evaluation when the requested path resolves to a file already included during the current execution. The once check recognizes files previously loaded through include, require, include_once, or require_once. require_once returns true in this skipped case. This prevents repeated declarations and side effects, but it does not undo anything performed by the first evaluation.
What are the production tradeoffs between require_once and Composer autoloading?
require_once resolves the file request, checks PHP records of included files, and immediately loads and evaluates the file when it has not already been included. Composer autoloading performs a lookup when PHP requests a class, so unused class files normally remain unloaded. This improves organization and can reduce unnecessary class file loading. In production, an optimized class map gives direct paths for known classes. The tradeoff is that deployment must include the generated autoloader and regenerate it when relevant autoload mappings or class files change.
20. What are traits in PHP, and how are method conflicts resolved?Language SpecificMedium
i Question Details
Explain horizontal code reuse, multiple traits, insteadof, aliases, visibility changes, limitations, and when composition is clearer.
Short Interview Answer (30-60 seconds)
Traits let PHP classes reuse methods and other members without inheriting from a common parent. A class can use multiple traits. If two imported traits contain a method with the same name, PHP produces a fatal error unless the conflict is resolved. I use insteadof to choose which implementation keeps the original name. I use as to add an alias or change visibility. Traits suit small shared behavior, while composition is clearer for behavior with dependencies, important state, or a separate responsibility.
Traits let several PHP classes share the same behavior even when those classes do not have the same parent. A trait can provide reusable methods and other class members. A class includes them with a use statement. When two included traits provide a method with the same name, PHP requires the developer to choose which one should be used. The other method can still receive another name. This keeps the choice clear and prevents PHP from silently selecting unexpected behavior.
Useful Questions to Ask the Interviewer
Should I demonstrate both insteadof and as?
Should I include a visibility change in the example?
Should I compare traits with object composition?
How to Explain It in an Interview
Traits provide horizontal code reuse. This means a class can include reusable behavior without extending another class. PHP supports only one parent class, but one class can use several traits.
A trait is declared with the trait keyword and imported into a class with use. Its methods behave as methods of the using class. A method declared directly in the class takes priority over a trait method. A trait method takes priority over a method inherited from a parent class.
If two imported traits define the same method name, PHP produces a fatal error unless the collision is explicitly resolved. The order of traits in the use statement does not choose a winner. The insteadof operator selects which trait implementation keeps the original method name. It excludes the competing implementation from that name within the using class.
The as operator adds another name for a trait method or changes its visibility. It does not rename or remove the original method. An alias can also have a different visibility. For example, a public trait method can receive a private alias while the original method remains public. Visibility can also be changed without creating a new name.
Traits can contain abstract methods, properties, static members, and constants. A trait cannot be instantiated and does not create a separate object. It also does not define a type contract. An interface should be used when callers need a guaranteed public API.
Method conflict operators resolve method collisions only. Trait properties and constants have separate compatibility rules. Conflicting declarations can cause a fatal error when their type, visibility, value, readonly status, or final status is incompatible.
Traits work best for small and closely related behavior. Composition is clearer when behavior has constructor dependencies, important mutable state, external communication, or several replaceable implementations. A separate object makes the dependency visible and easier to test.
Imported trait methods have normal class method behavior. Traits do not allocate a separate helper object for each instance. However, instance properties declared by a trait become properties of each using object and therefore use memory like other instance properties.
Example
The example uses FileWriter and ScreenWriter, which both define write. ReportWriter selects FileWriter::write with insteadof, so calling write uses the file implementation. It then creates a private alias named writeToScreen for ScreenWriter::write. The alias does not remove or rename the original ScreenWriter method inside the trait. The public writeBoth method can call the private alias because it is inside ReportWriter. Running the code first prints one file message. It then prints a second file message followed by a screen message.
Traits are useful when several unrelated PHP classes need a small shared implementation. Examples include formatting values, creating audit messages, normalizing input, exposing framework integration methods, or sharing a small group of utility methods that naturally belong to each class. Composition is usually better when the behavior needs services such as a logger, database connection, HTTP client, or configuration object. It is also better when the behavior owns important state, must be replaced during testing, or represents a separate business responsibility.
Why Interviewers Ask This
Interviewers ask this question to check whether a candidate understands code reuse in a language that supports only one parent class. They also test whether the candidate knows PHP method precedence, can resolve trait method collisions with insteadof and as, understands aliases and visibility changes, recognizes trait limitations, and can choose composition when shared behavior has its own state or dependencies.
Common interview mistakes
A common mistake is expecting PHP to select the first trait listed when two traits define the same method. PHP instead reports a fatal error until the collision is resolved. Another mistake is using as to choose the winning implementation. The winner is selected with insteadof, while as adds an alias or changes visibility. Developers may also believe that an alias removes the original method, but it creates an additional name. Other mistakes include treating a trait as an interface, calling a trait a second parent class, hiding service dependencies inside a trait, or placing too much state and unrelated behavior in one trait. Property and constant conflicts must also satisfy their own compatibility rules and cannot be resolved with insteadof.
Interview tip
Begin by saying that traits provide horizontal code reuse because PHP allows only one parent class. Then explain that unresolved duplicate trait methods cause a fatal error, insteadof chooses the implementation, and as adds an alias or changes visibility. Mention class, trait, and parent method precedence. Finish by explaining that traits suit small shared behavior, while composition is clearer for stateful behavior with dependencies.
Interviewer may ask next
What happens if two used traits define the same method and the class does not use insteadof?
PHP produces a fatal error because the method collision remains unresolved. PHP does not use the order in the use statement to choose an implementation. The class must explicitly select one method with insteadof or change the design so the conflicting methods are not imported together. This matters because an automatic choice could silently change behavior when a trait is added or modified.
When should composition be preferred over a trait?
Composition should be preferred when the behavior has its own responsibility, constructor dependencies, important mutable state, external communication, or interchangeable implementations. The class receives a separate object and calls it explicitly. This makes dependencies visible and makes replacement during testing easier. The tradeoff is an additional object and explicit delegation calls, but the design usually has clearer boundaries and is safer to maintain than a large stateful trait.
More questions load as you scroll
Disclaimer: This interview guide is for educational and informational purposes only. It is designed to help readers prepare, but it does not guarantee any interview result, hiring decision, offer, or outcome. Interview questions, hiring criteria, and preferred answers can vary by employer, interviewer, industry, location, and time. The examples and explanations reflect the authors' research and judgment, are provided without warranties of any kind, and should not be treated as the only correct approach. Diagrams are simplified illustrations intended to highlight the main components and their interactions; actual systems and implementations may be more complex. Alternative approaches may be equally valid or better suited to a particular question, context, or interviewer. To the fullest extent permitted by applicable law, the author, contributors, and publisher are not liable for decisions made, actions taken, or losses incurred based on this guide.