0% found this document useful (0 votes)
2 views

Common Q sets

The document covers various programming concepts and technologies, including multiple inheritance in PHP, RESTful APIs, API authentication and authorization, asynchronous programming in JavaScript, and more. It provides detailed explanations and examples for topics such as traits, dependency injection, and design patterns like MVC and Singleton. Additionally, it includes a comprehensive set of questions and answers on tools like Jenkins, PHPUnit, and Composer, as well as PHP 8 features and Git workflows.

Uploaded by

Sudhanshu Saxena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Common Q sets

The document covers various programming concepts and technologies, including multiple inheritance in PHP, RESTful APIs, API authentication and authorization, asynchronous programming in JavaScript, and more. It provides detailed explanations and examples for topics such as traits, dependency injection, and design patterns like MVC and Singleton. Additionally, it includes a comprehensive set of questions and answers on tools like Jenkins, PHPUnit, and Composer, as well as PHP 8 features and Git workflows.

Uploaded by

Sudhanshu Saxena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Multiple inheritance in php, how can we achieve multiple inheritance in php?

What is interface and abstract classes?

What is Dependency injection?

Describe traits.

RestFul APi?

• GET: This is used for fetching details from the server and is basically a read-only
operation.
• POST: This method is used for the creation of new resources on the server.
• PUT: This method is used to update the old/existing resource on the server or to
replace the resource.
• DELETE: This method is used to delete the resource on the server.
• PATCH: This is used for modifying the resource on the server.
• OPTIONS: This fetches the list of supported options of resources present on the
server.
What is API authentication?

API authentication verifies that a user is who they claim to be. There are
many types of API authentication.

1. API Key-value
2. Token
3. Oauth 2 SSO
4. Bearer Token

What is API authorization?

After you prove the user's identity, you can check which data that user is
allowed to access. That process is authorization. Authorization ensures
that the user is authorized to view or edit a specific set of data.

--> JavaScript is synchronous by default, but it has powerful features


that allow you to write asynchronous code.
Here's the breakdown:

Synchronous:

JavaScript code executes line by line, one operation at a time. This


means that each line of code must finish executing before the next line
begins.

Asynchronous:

Asynchronous code allows you to perform operations that may take


some time (like fetching data from a server) without blocking the rest of
your program. When an asynchronous operation starts, your program
can continue running other code while it waits for the operation to
complete.

Key Asynchronous Features in JavaScript:

Callbacks:

These are functions that are passed as arguments to other functions and
are executed when the asynchronous operation completes.

Promises:

A more structured way to handle asynchronous operations. Promises


represent the eventual result of an asynchronous operation and allow
you to chain multiple operations together.

Async/Await:

A syntax that makes asynchronous code look more like synchronous


code, making it easier to read and write.
---- > $array = [1,4,5,5,7,888,98];

Employees table

employee_id employee_name manager_id


1 John Doe NULL
2 Jane Smith 1
3 David Lee 1
4 Sarah Jones 2

find the names of employees and their respective managers,

Here is a question set based on the provided topics with answers. The
topics are categorized by their level of difficulty or expertise:

Jenkins - A

1. What is Jenkins and what is its primary purpose?


a. Answer: Jenkins is an open-source automation server that
facilitates continuous integration and continuous delivery
(CI/CD). It automates the process of building, testing, and
deploying applications.
2. How do you create a pipeline in Jenkins?
a. Answer: You create a pipeline in Jenkins by defining a
Jenkinsfile that contains the instructions for building and
deploying the project. The Jenkinsfile can be written using
either declarative or scripted pipeline syntax.

PHP 8 - A

1. What new features were introduced in PHP 8?


a. Answer: PHP 8 introduced several new features, including:
i. Union types
ii. Named arguments
iii. Attributes (annotations)
iv. Constructor property promotion
v. Match expressions
vi. Just-in-time (JIT) compilation
2. What are Named Arguments in PHP 8?
a. Answer: Named arguments allow you to pass arguments to a
function or method by explicitly specifying the parameter
names. This enables passing arguments in any order and
improving readability.

GIT - PA (Proficiency/Advanced)

1. What is a Git workflow, and what are the common types?


a. Answer: A Git workflow is a set of guidelines for working with
Git repositories in teams. Common workflows include:
i. Feature branching
ii. Gitflow workflow
iii. Forking workflow
2. How do you resolve merge conflicts in Git?
a. Answer: Merge conflicts occur when changes made in
different branches cannot be automatically merged. To
resolve them, you must manually edit the conflicting files,
then mark the conflicts as resolved using git add, and finally
commit the changes.

Cherry-pick - PA

1. What does the git cherry-pick command do?


a. Answer: The git cherry-pick command applies the changes
from a specific commit from one branch to another. It is
useful when you want to apply a single commit from a
different branch without merging the entire branch.

Git Fork - PA

1. What is the difference between cloning and forking a Git


repository?
a. Answer: Cloning a repository creates a copy of the repository
locally, while forking a repository creates a copy on your Git
hosting service (e.g., GitHub), allowing you to make changes
without affecting the original repository.

XDebug - NA (Not Applicable)

• Note: No questions provided for XDebug as it's marked as NA.

Profilers - NA

• Note: No questions provided for Profilers as it's marked as NA.


PHPUnit - PA

1. How do you run PHPUnit tests in your project?


a. Answer: You can run PHPUnit tests by executing the
command php vendor/bin/phpunit in your project directory.
This will run all tests in the tests folder by default.
2. What is the difference between assertEquals() and
assertSame() in PHPUnit?
a. Answer: assertEquals() checks if two values are equal,
regardless of their types, while assertSame() checks if two
values are equal and of the same type.

Composer - A

1. What is Composer and how does it work?


a. Answer: Composer is a dependency management tool for
PHP. It allows you to declare the libraries your project
depends on and manages installing and updating them
automatically.
2. What is the purpose of the composer.json file?
a. Answer: The composer.json file defines the dependencies
for a PHP project, including package names, versions, and
other configuration settings such as autoloading and scripts.

Named Arguments - A

1. How do named arguments improve function calls in PHP 8?


a. Answer: Named arguments allow passing arguments to a
function by explicitly specifying their parameter names. This
makes the function calls more readable and allows
parameters to be passed in any order.

Type Hinting - A

1. What is type hinting in PHP, and why is it useful?


a. Answer: Type hinting in PHP allows you to specify the
expected data types for function parameters and return
values. This helps ensure that functions are used correctly
and reduces runtime errors.

Return Type Arguments - A

1. What are return type declarations in PHP?


a. Answer: Return type declarations specify the type of value a
function is expected to return. For example, public function
getUser(): User {} ensures that the function returns a User
object.

PSR - A

1. What is PSR, and why is it important in PHP development?


a. Answer: PSR (PHP Standards Recommendations) is a set of
standards that define how PHP code should be written. PSR
helps ensure interoperability and consistency between
different libraries and frameworks.

PHP Autoloading - A

1. How does autoloading work in PHP?


a. Answer: Autoloading in PHP is the process of automatically
including class files when a class is instantiated. The
spl_autoload_register() function is used to register an
autoloader, allowing classes to be loaded on-demand.

Namespaces - A

1. What are namespaces in PHP?


a. Answer: Namespaces in PHP are used to group related
classes, interfaces, functions, and constants. They help
avoid name collisions between classes with the same name
in different libraries.

PHP Upgrade Experience - A

1. What are the key considerations when upgrading PHP versions


in a production environment?
a. Answer: Key considerations include:
i. Compatibility with existing code (test thoroughly)
ii. Backup existing configurations and databases
iii. Update dependencies (e.g., Composer packages)
iv. Address deprecations and breaking changes

Laravel Upgrade Experience - PA

1. What steps are involved in upgrading a Laravel application?


a. Answer: Upgrading Laravel typically involves:
i. Updating dependencies in composer.json
ii. Running composer update
iii. Checking for deprecated features
iv. Updating configuration files and routes
v. Testing the application for any issues

Method Overloading - PA

1. What is method overloading in PHP?


a. Answer: Method overloading allows a class to define
multiple methods with the same name but different
parameter types or numbers. In PHP, this is achieved using
magic methods like __call().

Multiple Inheritance - A

1. Does PHP support multiple inheritance?


a. Answer: PHP does not support multiple inheritance directly.
However, multiple inheritance can be achieved using traits
or by using interfaces.

Traits - A

1. What are traits in PHP, and why are they useful?


a. Answer: Traits are a mechanism for code reuse in PHP. They
allow you to define methods that can be used in multiple
classes. Traits help overcome the limitation of single
inheritance in PHP.

Abstract Class/Interface - A

1. What is the difference between an abstract class and an


interface in PHP?
a. Answer: An abstract class can have both abstract methods
(without implementation) and concrete methods (with
implementation). An interface only defines method
signatures without any implementation. A class can
implement multiple interfaces but can extend only one
abstract class.

PHPCS, PHPMD, PHPCPD - PA

1. What are PHPCS, PHPMD, and PHPCPD, and how are they
useful in PHP development?
a. Answer:
i. PHPCS (PHP CodeSniffer): Ensures that PHP code
adheres to a coding standard.
ii. PHPMD (PHP Mess Detector): Detects potential issues
and design problems in PHP code.
iii. PHPCPD (PHP Copy Paste Detector): Identifies
duplicate code blocks in PHP codebases.

Sessions - A

1. How do you manage sessions in PHP?


a. Answer: PHP sessions are managed using the $_SESSION
superglobal. To start a session, you use session_start(). Data
can be stored and retrieved from the session using
$_SESSION['key'].

GuzzleHTTP - A

1. What is Guzzle, and how do you use it in PHP?


a. Answer: Guzzle is a PHP HTTP client library that allows you to
send HTTP requests and handle responses. It provides a
simple API for sending requests, handling responses, and
working with HTTP headers, cookies, and other features.

Basic Auth - A

1. How do you implement basic authentication in PHP?


a. Answer: Basic authentication in PHP can be implemented by
sending a username and password in the Authorization
header. You can use the $_SERVER['PHP_AUTH_USER'] and
$_SERVER['PHP_AUTH_PW'] superglobals to retrieve the
credentials.

CURL - A

1. How do you use CURL in PHP?


a. Answer: CURL in PHP is used to make HTTP requests. You
use curl_init() to initialize a CURL session, curl_setopt() to set
options, curl_exec() to execute the request, and curl_close()
to close the session.

Design Pattern - MVC, Singleton - A

1. What is the Singleton design pattern, and how is it used in PHP?


a. Answer: The Singleton pattern ensures that a class has only
one instance and provides a global point of access to it. This
is achieved by making the constructor private and providing a
static method to get the instance.
2. Explain the MVC pattern in the context of PHP.
a. Answer: The Model-View-Controller (MVC) pattern separates
an application into three components:
i. Model: Represents data and business logic.
ii. View: Displays the data.
iii. Controller: Handles user input and updates the model
and view accordingly.

SOLID - A

1. What are the SOLID principles in object-oriented programming?


a. Answer: SOLID is an acronym for five design principles that
help create maintainable and flexible software:
i. S: Single Responsibility Principle
ii. O: Open/Closed Principle
iii. L: Liskov Substitution Principle
iv. I: Interface Segregation Principle
v. D: Dependency Inversion Principle

OAuth - Basics

1. What is OAuth, and how does it work?


a. Answer: OAuth is an open standard for access delegation. It
allows third-party applications to access user resources
without exposing their credentials. OAuth uses tokens for
authentication instead of passwords.

CI/CD Jenkins - PA

1. What is the role of Jenkins in Continuous Integration and


Continuous Delivery?
a. Answer: Jenkins automates the process of integrating code
changes and deploying applications. It monitors version
control repositories, runs tests, and deploys applications in
various environments as part of the CI/CD pipeline.

MySQL - Joins - A

1. What is the difference between an INNER JOIN and a LEFT JOIN


in MySQL?
a. Answer:
i. INNER JOIN: Returns rows that have matching values in
both tables.
ii. LEFT JOIN: Returns all rows from

the left table and matching rows from the right table. If there is no
match, NULL values are returned for the right table's columns.

Angular - A

1. What is Lazy Loading in Angular?


a. Answer: Lazy loading in Angular is a design pattern that
allows you to load modules only when they are needed,
improving the initial load time of an application.

JS - Event Loop

1. What is the event loop in JavaScript, and how does it work?


a. Answer: The event loop is responsible for executing
asynchronous callbacks in JavaScript. It continuously checks
the call stack for pending tasks and processes them in a non-
blocking manner.

Here’s a comprehensive set of questions and answers based on the


provided topics:

Jenkins

1. Q: What is Jenkins and how is it used in continuous integration


(CI)?
a. A: Jenkins is an open-source automation server used to
automate various tasks in software development, including
building, testing, and deploying code. It supports continuous
integration (CI) by integrating with version control systems
and running jobs automatically whenever changes are made.
2. Q: How do you install Jenkins?
a. A: Jenkins can be installed via package managers like apt or
yum on Linux, or downloaded as a WAR file to run directly
with java -jar jenkins.war. It's also available as a Docker
image.

PHP 8

1. Q: What are the main features introduced in PHP 8?


a. A: PHP 8 introduces several new features such as Named
Arguments, Union Types, Attributes (Annotations), JIT (Just In
Time) compiler, Match Expressions, Constructor Property
Promotion, and improvements in performance and error
handling.
GIT

1. Q: What is the difference between git pull and git fetch?


a. A: git fetch downloads changes from the remote repository
but doesn't automatically merge them into the local branch.
git pull fetches the changes and merges them with the local
branch.
2. Q: How can you revert a commit in Git?
a. A: You can use git revert <commit> to create a new commit
that undoes the changes made by the specified commit.

Cherry-pick

1. Q: What is the use of git cherry-pick?


a. A: git cherry-pick allows you to apply changes from a specific
commit from one branch into another branch, without
merging the entire branch.

Git Fork

1. Q: What is a Git Fork and when would you use it?


a. A: A fork in Git is a copy of a repository that allows you to
freely experiment with changes without affecting the original
project. It’s commonly used in open-source projects when
contributing.

XDebug

1. Q: How does XDebug help in debugging PHP applications?


a. A: XDebug is a powerful debugger and profiler for PHP. It
allows step-debugging, stack traces, variable inspection, and
performance profiling to identify bugs and bottlenecks in the
code.
Profilers

1. Q: What is the purpose of a profiler in PHP?


a. A: A profiler collects detailed performance data about an
application, helping developers identify bottlenecks and
optimize code. XDebug and Blackfire are popular profilers in
PHP.

PHPUnit

1. Q: What is PHPUnit and why is it important?


a. A: PHPUnit is a testing framework for PHP that allows
developers to write and run unit tests. It helps ensure code
quality by automatically running tests to validate
functionality.

Composer

1. Q: What is Composer and how does it benefit PHP developers?


a. A: Composer is a dependency manager for PHP that allows
developers to manage project libraries and dependencies. It
simplifies the process of installing, updating, and
autoloading PHP packages.

Named Arguments

1. Q: What are named arguments in PHP 8?


a. A: Named arguments allow you to pass arguments to a
function or method by specifying the parameter names,
rather than relying on the order of arguments. This makes
code more readable and flexible.
Type Hinting

1. Q: What is type hinting in PHP?


a. A: Type hinting is a feature in PHP where you specify the
expected type of a function or method’s parameters and
return values. It helps in improving code quality by preventing
type-related errors.

Return Type Arguments

1. Q: How does PHP 8 handle return type declarations?


a. A: PHP 8 allows developers to specify return types for
functions and methods, which helps ensure that the correct
type is returned and improves code clarity.

PSR

1. Q: What is PSR and why is it important in PHP development?


a. A: PSR (PHP Standard Recommendation) is a set of
guidelines and standards that promote interoperability
between PHP frameworks and libraries. Examples include
PSR-1 (Basic Coding Standard) and PSR-4 (Autoloading
Standard).

PHP AutoLoading

1. Q: What is autoloading in PHP?


a. A: Autoloading in PHP allows classes to be loaded
automatically when they are needed, without having to
include or require them manually. This is typically achieved
via the spl_autoload_register() function or Composer’s
autoloader.
Namespaces

1. Q: What are namespaces in PHP and why are they useful?


a. A: Namespaces in PHP provide a way to encapsulate code to
avoid name collisions between classes, functions, and
constants. They help organize and structure code in large
applications.

PHP Upgrade Experience

1. Q: What are the common challenges when upgrading PHP


versions?
a. A: Common challenges include deprecated functions,
incompatibility with older extensions or libraries, changes in
language features, and potential performance issues after
upgrading.

Laravel Upgrade Experience

1. Q: What should you consider when upgrading a Laravel


application?
a. A: When upgrading a Laravel application, it's important to
check for deprecated methods, ensure compatibility with
new versions of dependencies, and follow the Laravel
upgrade guide to address any breaking changes.

Method Overloading

1. Q: How does PHP handle method overloading?


a. A: PHP does not support traditional method overloading, but
it allows dynamic method calls using __call() to handle calls
to undefined methods.
Multiple Inheritance

1. Q: How does PHP handle multiple inheritance?


a. A: PHP does not support multiple inheritance directly.
However, it allows multiple inheritance-like behavior through
the use of interfaces and traits.

Traits

1. Q: What is a trait in PHP and how is it different from a class?


a. A: A trait is a mechanism for code reuse in PHP. It allows you
to share methods across multiple classes without requiring
inheritance. Unlike a class, a trait cannot be instantiated on
its own.

Abstract Class/Interface

1. Q: What is the difference between an abstract class and an


interface in PHP?
a. A: An abstract class can contain both abstract and concrete
methods, while an interface only contains method signatures
without implementations. A class can implement multiple
interfaces but inherit from only one abstract class.

PHPCS, PHPMD, PHPCPD

1. Q: What are PHPCS, PHPMD, and PHPCPD?


a. A: These are PHP tools for maintaining code quality. PHPCS
(PHP Code Sniffer) checks code against coding standards,
PHPMD (PHP Mess Detector) detects potential bugs and
suboptimal code, and PHPCPD (PHP Copy/Paste Detector)
identifies duplicate code.
Sessions

1. Q: How do sessions work in PHP?


a. A: Sessions in PHP are used to store data across multiple
page requests. PHP uses a session ID, typically stored in a
cookie, to associate client requests with stored session data.

GuzzleHTTP

1. Q: What is GuzzleHTTP?
a. A: GuzzleHTTP is a PHP HTTP client that allows you to send
HTTP requests, handle responses, and integrate with APIs. It
supports features like asynchronous requests and
middleware.

Basic Auth

1. Q: What is Basic Authentication in HTTP?


a. A: Basic Authentication is a method for an HTTP client to
send a username and password in the request header to
authenticate the user. It’s not recommended for production
as credentials are sent in clear text unless used with HTTPS.

CURL

1. Q: What is cURL in PHP?


a. A: cURL is a library and command-line tool for transferring
data with URLs. In PHP, it’s commonly used to send HTTP
requests to external servers.

Design Patterns

1. Q: What is the Singleton Design Pattern?


a. A: The Singleton Pattern ensures that a class has only one
instance and provides a global point of access to that
instance. It’s often used for managing shared resources.

SOLID

1. Q: What are the SOLID principles?


a. A: SOLID is a set of five design principles to improve software
maintainability:
i. S: Single Responsibility Principle
ii. O: Open/Closed Principle
iii. L: Liskov Substitution Principle
iv. I: Interface Segregation Principle
v. D: Dependency Inversion Principle

OAuth

1. Q: What is OAuth and when is it used?


a. A: OAuth is an open standard for authorization. It allows
third-party applications to access a user's resources without
sharing credentials. It’s commonly used for allowing access
to APIs on behalf of users.

CI/CD Jenkins

1. Q: What is the role of Jenkins in a CI/CD pipeline?


a. A: Jenkins automates the process of building, testing, and
deploying code, ensuring that new changes are integrated
into the project seamlessly and that code is delivered to
production in a consistent manner.
MySQL - Joins

1. Q: What is the difference between INNER JOIN and LEFT JOIN in


MySQL?
a. A: An INNER JOIN returns only the rows that have matching
values in both tables. A LEFT JOIN returns all rows from the
left table, along with matching rows from the right table; if
there is no match, NULL values are returned.

Angular

1. Q: What is Angular?
a. A: Angular is a platform and framework for building single-
page web applications (SPAs) using TypeScript and other web
technologies. It provides tools for building efficient, scalable
web apps with features like two-way data binding and
dependency injection.

Interceptors

1. Q: What are Angular interceptors?


a. A: Interceptors are used to modify HTTP requests and
responses in Angular. They allow you to add headers, handle
errors, or log data before a request is sent or after a response
is received.

LazyLoading

1. Q: What is Lazy Loading in Angular?


a. A: Lazy loading is a technique in Angular to load modules only
when they are needed, rather than loading them all at once.
This improves performance by reducing the initial load time
of the application.
NgRx

1. Q: What is NgRx in Angular?


a. A: NgRx is a reactive state management library for Angular
based on Redux principles. It provides a store to manage
application state, actions to modify the state, and reducers
to handle these actions.

JavaScript

1. Q: What is the Event Loop in JavaScript?


a. A: The event loop is responsible for executing code,
collecting and processing events, and executing queued sub-
tasks. It allows JavaScript to be non-blocking and
asynchronous.
2. Q: What is the difference between on and click in JavaScript
event handling?
a. A: The on is a generic prefix used for event listeners (like
onclick, onmouseover, etc.), while .click() is a method to
trigger a click event programmatically.
3. Q: What are Promises in JavaScript?
a. A: A Promise is an object representing the eventual
completion (or failure) of an asynchronous operation. It
allows chaining of .then() and .catch() to handle success or
failure results.
4. Q: What is Event Propagation in JavaScript?
a. A: Event propagation refers to the way events bubble up or
trickle down the DOM tree when an event is triggered. It can
be controlled using stopPropagation() and preventDefault()
methods.
Here’s a fresh set of programming questions along with answers that
cover various concepts and techniques:

Jenkins

1. Q: How can you trigger a Jenkins job after a successful Git


commit?
a. A: You can configure a Jenkins job to be triggered
automatically after a successful Git commit by setting up a
webhook in GitHub or GitLab, which will notify Jenkins to
start the job when changes are pushed to the repository.
2. Q: How do you set up a Jenkins pipeline?
a. A: A Jenkins pipeline is typically defined in a Jenkinsfile. In the
file, you define stages and steps using a declarative or
scripted pipeline syntax. You then link the Jenkinsfile to your
repository and Jenkins will execute the pipeline when
changes are made.

PHP 8

1. Q: Write a PHP function that returns the sum of all elements in


an array, using a named argument.
a. A: function sumArray(array $numbers): int {
return array_sum($numbers);
}

$total = sumArray(numbers: [1, 2, 3, 4]);


echo $total; // 10

2. Q: How would you handle a deprecation warning in PHP 8 when


using a deprecated function?
a. A: In PHP 8, you can suppress deprecation warnings using @
(error suppression operator), but it's better to update the
code to avoid deprecated functions. For instance, replace
create_function() with anonymous functions.

GIT

1. Q: Write a Git command to check the status of your working


directory.
a. A: git status
2. Q: How would you merge a feature branch into the main branch
in Git?
a. A: git checkout main
git pull origin main
git merge feature-branch
git push origin main

Cherry-pick

1. Q: How do you cherry-pick a commit from another branch in


Git?
a. A: Use the command git cherry-pick <commit-hash>. This
applies the changes of the specified commit to the current
branch.
git cherry-pick <commit-hash>

XDebug

1. Q: How would you set up XDebug for remote debugging in PHP?


a. A: You need to configure your php.ini file to enable XDebug
for remote debugging. Example configuration:
zend_extension=xdebug.so
xdebug.remote_enable=1
xdebug.remote_host=localhost
xdebug.remote_port=9000
xdebug.remote_autostart=1

PHPUnit

1. Q: Write a basic PHPUnit test for a function that adds two


numbers.
a. A: class MathTest extends PHPUnit\Framework\TestCase {
public function testAdd() {
$this->assertEquals(5, add(2, 3));
}
}

function add($a, $b) {


return $a + $b;
}
2. Q: How do you run all tests in a directory using PHPUnit?
a. A: Use the following command: php vendor/bin/phpunit --
testdox tests/

Composer

1. Q: How do you install a specific version of a package using


Composer?
a. A: You can install a specific version of a package using the
command: composer require vendor/package:^1.2.3

2. Q: How do you autoload PHP classes using Composer?


a. A: Composer automatically generates an autoloader for you.
You just need to include vendor/autoload.php in your PHP
script: require 'vendor/autoload.php';

PHP AutoLoading

1. Q: What’s the difference between require_once and


autoloading in PHP?
a. A: require_once explicitly includes a file that contains the
class definition. Autoloading, on the other hand,
automatically loads the class files when needed without
requiring you to manually include them.

PHP Upgrade Experience

1. Q: What are common issues that arise when upgrading PHP to


version 8?
a. A: Some common issues are the deprecation of functions,
removal of some features (like create_function()), and
compatibility issues with third-party libraries or frameworks
that haven't been updated to support PHP 8.

Method Overloading

1. Q: Write a PHP class that simulates method overloading using


the __call magic method.
a. A: class MyClass {
public function __call($method, $args) {
echo "Method {$method} called with arguments: " .
implode(', ', $args);
}
}

$obj = new MyClass();


$obj->hello('world'); // Outputs: Method hello called with
arguments: world

SOLID Principles

1. Q: How does the Open/Closed Principle apply to software


design?
a. A: The Open/Closed Principle states that software entities
(classes, modules, functions) should be open for extension
but closed for modification. This means that the behavior of a
class can be extended without modifying its existing code.

PHP Design Patterns

1. Q: Implement a Singleton pattern in PHP.


a. A: class Singleton {
private static $instance = null;

private function __construct() {}

public static function getInstance() {


if (self::$instance === null) {
self::$instance = new Singleton();
}
return self::$instance;
}
}

$singleton = Singleton::getInstance();

MySQL

1. Q: Write a query to retrieve all users who have made more than
5 purchases from the database.
a. A: SELECT users.name, COUNT(purchases.id) AS
purchase_count
FROM users
JOIN purchases ON users.id = purchases.user_id
GROUP BY users.id
HAVING purchase_count > 5;

Angular

1. Q: How do you implement lazy loading in Angular?


a. A: You can configure lazy loading by setting up routing with
the loadChildren property in the routing module: const
routes: Routes = [
{
path: 'lazy',
loadChildren: () => import('./lazy/lazy.module').then(m =>
m.LazyModule)
}
];

JavaScript Promises

1. Q: How do you handle asynchronous code with Promises in


JavaScript?
a. A: function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("Data fetched"), 1000);
});
}

fetchData().then(data => {
console.log(data);
}).catch(error => {
console.log(error);
});

Event Propagation

1. Q: How do you stop event propagation in JavaScript?


a. A:
document.getElementById("button").addEventListener("click
", function(event) {
event.stopPropagation(); // Stops the event from bubbling
up the DOM
alert("Button clicked!");
});

CURL in PHP

1. Q: How do you make a GET request with cURL in PHP?


a. A: $ch = curl_init('https://api.example.com/data');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;

OAuth

1. Q: How would you implement OAuth 2.0 for API authentication


in PHP?
a. A: You would need to follow the OAuth flow:
i. Redirect the user to the OAuth authorization URL.
ii. The user authorizes the app and is redirected back with
an authorization code.
iii. Exchange the authorization code for an access token
using a POST request.
Basic Auth

1. Q: How can you send HTTP Basic Authentication headers in


PHP?
a. A: $url = "https://api.example.com/endpoint";
$username = "user";
$password = "password";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD,
"$username:$password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;

Here’s another set of programming questions, including React JS topics


as well:

Jenkins

1. Q: How would you configure Jenkins to automatically build and


test code on every commit?
a. A: You can configure Jenkins by creating a job with a Git
repository integration. Then, you would set up a webhook in
your Git provider (like GitHub) to trigger the Jenkins job every
time a commit is pushed to the repository.
2. Q: What is the difference between declarative and scripted
pipelines in Jenkins?
a. A: In declarative pipelines, you use a more structured syntax
to define the pipeline stages and steps, whereas scripted
pipelines allow for more flexibility and control with a full
Groovy-based script.

PHP 8

1. Q: Write a PHP function to check if a string is a palindrome in


PHP 8.
a. A: function isPalindrome(string $str): bool {
$str = preg_replace("/[^a-zA-Z0-9]/", "", strtolower($str));
return $str === strrev($str);
}
echo isPalindrome("A man a plan a canal Panama"); // true

2. Q: How would you implement a union type in PHP 8 for a


function that accepts both integers and strings?
a. A: function processInput(int|string $input): string {
return "Processing " . (string) $input;
}
echo processInput(5); // "Processing 5"
echo processInput("Hello"); // "Processing Hello"

GIT

1. Q: How do you undo the last commit in Git without losing your
changes?
a. A: Use the git reset command with the --soft option: git reset -
-soft HEAD~1

2. Q: How can you list all branches, both local and remote, in Git?
a. A: Use the following command: git branch -a
PHPUnit

1. Q: How do you test a function that retrieves data from a


database in PHPUnit?
a. A: You can use PHPUnit’s mocking capabilities to mock
database calls or use a test database to run tests. Example:
class UserRepositoryTest extends
PHPUnit\Framework\TestCase {
public function testFindUser() {
$mockDb = $this-
>createMock(DatabaseConnection::class);
$mockDb->method('query')->willReturn(['id' => 1, 'name'
=> 'John Doe']);

$repo = new UserRepository($mockDb);


$user = $repo->findUser(1);
$this->assertEquals('John Doe', $user['name']);
}
}

React JS

1. Q: What is JSX in React?


a. A: JSX (JavaScript XML) is a syntax extension for JavaScript
that allows you to write HTML-like code inside JavaScript. It’s
used in React to describe what the UI should look like.
const element = <h1>Hello, world!</h1>;

2. Q: How do you pass data from a parent component to a child


component in React?
a. A: Data is passed from parent to child using props.
function Parent() {
return <Child message="Hello from Parent" />;
}

function Child(props) {
return <h1>{props.message}</h1>;
}

3. Q: What is the purpose of the useState hook in React?


a. A: The useState hook is used to add state to functional
components in React. It returns a state variable and a
function to update that variable.
const [count, setCount] = useState(0);

function increment() {
setCount(count + 1);
}

4. Q: How do you manage side effects in React?


a. A: You manage side effects in React using the useEffect
hook. This hook is run after every render and can be used for
tasks like data fetching or updating the DOM.
useEffect(() => {
// Code that runs after the component mounts
fetchData();
}, []); // Empty array means it runs once when the component mounts
React Component Lifecycle

1. Q: What are the different lifecycle methods in React class


components?
a. A: The main lifecycle methods are:
i. componentDidMount() – Called after the component
mounts.
ii. componentDidUpdate() – Called after the component
updates.
iii. componentWillUnmount() – Called before the
component is removed from the DOM.
2. Q: How do you handle errors in React components?
a. A: You handle errors using the componentDidCatch method
in class components or the ErrorBoundary component in
functional components: class ErrorBoundary extends
React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}

static getDerivedStateFromError(error) {
return { hasError: true };
}

componentDidCatch(error, info) {
console.log(error, info);
}

render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}

JavaScript Promises

1. Q: How can you handle multiple asynchronous tasks


sequentially using JavaScript promises?
a. A: You can chain promises to ensure tasks run in sequence:
fetchData()
.then(result => processData(result))
.then(processedData => displayData(processedData))
.catch(error => console.error(error));

2. Q: What is the difference between async/await and promises in


JavaScript?
a. A: async/await is syntactic sugar built on top of promises. It
allows you to write asynchronous code in a synchronous
style, making it easier to read and manage.
async function fetchData() {
let response = await fetch('https://api.example.com');
let data = await response.json();
return data;
}
MySQL

1. Q: How do you perform a JOIN between two tables in MySQL?


a. A: You can perform an inner join between two tables like this:
SELECT users.name, orders.amount
FROM users
JOIN orders ON users.id = orders.user_id;

2. Q: What’s the difference between INNER JOIN and LEFT JOIN?


a. A: INNER JOIN returns only the rows with matching values in
both tables, while LEFT JOIN returns all rows from the left
table and matched rows from the right table. If there is no
match, the result will include NULLs for the right table’s
columns.

OAuth

1. Q: What is the OAuth authorization code flow?


a. A: In the OAuth authorization code flow, the client first
redirects the user to the authorization server, where the user
grants access. The server then redirects the user back to the
client with an authorization code, which the client exchanges
for an access token to access the user’s data.

SOLID Principles

1. Q: How does the Dependency Inversion Principle work in


SOLID?
a. A: The Dependency Inversion Principle suggests that high-
level modules should not depend on low-level modules, but
both should depend on abstractions (e.g., interfaces). It
allows more flexibility by reducing coupling between
components.

PHP AutoLoading

1. Q: How does Composer handle autoloading in PHP?


a. A: Composer uses the autoload key in the composer.json file
to manage class autoloading. By default, it uses PSR-4 to
autoload classes based on their namespace and file
structure.
"autoload": {
"psr-4": {
"App\\": "src/"
}
}

CURL in PHP

1. Q: How can you make a POST request with data in PHP using
cURL?
a. A: $ch = curl_init('https://api.example.com/submit');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'name' => 'John',
'email' => '[email protected]'
]);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
Here’s another set of programming questions that covers various topics,
including React JS, PHP, Git, and more:

Jenkins

1. Q: How would you integrate Jenkins with Docker to create a


containerized build environment?
a. A: You can integrate Jenkins with Docker by using the Docker
plugin or configuring Jenkins to run inside a Docker container.
For example, you can create a Dockerfile for Jenkins, build
the Jenkins image, and then configure the Jenkins job to use
Docker containers as build environments by using the docker
command inside the pipeline.
docker run --rm -v $(pwd):/workspace jenkins/jenkins:lts

2. Q: How would you trigger a Jenkins job when a pull request is


opened in GitHub?
a. A: You can configure a GitHub webhook to trigger Jenkins
when a pull request is opened. This involves setting up a
GitHub webhook pointing to the Jenkins server and
configuring the Jenkins job to run on the pull request event
using a plugin like "GitHub Pull Request Builder".

PHP 8

1. Q: How do you use str_contains() function in PHP 8 to check if a


substring exists in a string?
a. A: $haystack = "Hello, world!";
$needle = "world";
if (str_contains($haystack, $needle)) {
echo "Substring found!";
} else {
echo "Substring not found!";
}

2. Q: What is the match expression in PHP 8 and how is it different


from switch?
a. A: The match expression is a new feature in PHP 8 that
provides a more powerful and expressive alternative to the
switch statement. Unlike switch, match:
i. Supports strict type checking.
ii. Can return values.
iii. Does not require break statements.
$status = 200;
$response = match ($status) {
200 => 'OK',
404 => 'Not Found',
default => 'Unknown status',
};

GIT

1. Q: How would you delete a remote branch in Git?


a. A: You can delete a remote branch with the following
command: git push origin --delete <branch-name>

2. Q: How do you resolve conflicts when merging two branches in


Git?
a. A: When a conflict occurs, Git will mark the conflicting files.
You can open the files, manually resolve the conflicts by
editing the sections marked by Git, and then stage and
commit the changes: git add <resolved-file>
git commit -m "Resolved merge conflict"

PHPUnit

1. Q: How do you run a specific test method using PHPUnit?


a. A: You can specify a particular test method to run using the --
filter option: php vendor/bin/phpunit --filter testMethodName

2. Q: How do you mock a class method in PHPUnit?


a. A: You can use PHPUnit’s createMock() method to mock a
class or method: $mock = $this-
>createMock(MyClass::class);
$mock->method('someMethod')->willReturn('mocked
value');
$this->assertEquals('mocked value', $mock-
>someMethod());

React JS

1. Q: What is the purpose of the useEffect hook in React?


a. A: The useEffect hook allows you to perform side effects in
functional components, such as data fetching,
subscriptions, or manually changing the DOM. It runs after
the render and can be controlled by dependencies to run only
when certain variables change.
useEffect(() => {
console.log("Component mounted");
}, []); // Empty array ensures it only runs on mount

2. Q: How can you handle form submission in React?


a. A: In React, form submission can be handled by defining an
onSubmit handler, which captures the form data and
performs necessary actions, such as sending the data to a
server.
function MyForm() {
const [name, setName] = useState('');

const handleSubmit = (event) => {


event.preventDefault();
alert('Form submitted: ' + name);
};

return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
);
}

3. Q: What is the difference between useState and useReducer in


React?
a. A: useState is for simple state updates, whereas useReducer
is more suitable for complex state logic that involves multiple
sub-values or when the next state depends on the previous
one. useReducer is more like a Redux-style state
management system.
// useState example
const [count, setCount] = useState(0);

// useReducer example
const initialState = { count: 0 };
const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
};
const [state, dispatch] = useReducer(reducer, initialState);

4. Q: What is React Context and when should it be used?


a. A: React Context provides a way to pass data through the
component tree without having to pass props down manually
at every level. It is best used for global state management
such as theming, authentication, or language preferences.
const ThemeContext = createContext('light');

function MyComponent() {
const theme = useContext(ThemeContext);
return <div className={`theme-${theme}`}>Hello, world!</div>;
}

MySQL

1. Q: How do you write a query to get the top 5 customers by total


amount spent from a customers table and an orders table?
a. A: SELECT customers.name, SUM(orders.amount) AS
total_spent
FROM customers
JOIN orders ON customers.id = orders.customer_id
GROUP BY customers.id
ORDER BY total_spent DESC
LIMIT 5;

2. Q: What is the difference between WHERE and HAVING in


MySQL?
a. A: WHERE is used to filter records before grouping (applies
before GROUP BY), whereas HAVING is used to filter records
after grouping (applies after GROUP BY).

SOLID Principles

1. Q: What does the Liskov Substitution Principle (LSP) state in


SOLID?
a. A: The Liskov Substitution Principle states that objects of a
superclass should be replaceable with objects of a subclass
without affecting the correctness of the program. This
ensures that derived classes can be substituted for base
classes without introducing errors.
OAuth

1. Q: How do you implement token-based authentication using


OAuth in a PHP application?
a. A: In token-based authentication, the client first sends the
user's credentials to the OAuth server to receive an access
token. The client can then use this token for subsequent
requests. Example: // Send request to OAuth server to get
token
$response =
file_get_contents('https://oauth.example.com/token', false,
stream_context_create([
'http' => [
'method' => 'POST',
'content' => http_build_query(['grant_type' => 'password',
'username' => 'user', 'password' => 'pass']),
]
]));

$token = json_decode($response)->access_token;

// Use token for API requests


$apiResponse =
file_get_contents('https://api.example.com/data', false,
stream_context_create([
'http' => [
'header' => 'Authorization: Bearer ' . $token,
]
]));
CURL in PHP

1. Q: How do you send a PUT request using cURL in PHP?


a. A: $ch = curl_init('https://api.example.com/resource');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['key'
=> 'value']));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:
application/json']);
$response = curl_exec($ch);
curl_close($ch);
echo $response;

Design Patterns

1. Q: Implement a Factory design pattern in PHP.


a. A: interface Animal {
public function speak();
}

class Dog implements Animal {


public function speak() {
return "Bark";
}
}

class Cat implements Animal {


public function speak() {
return "Meow";
}
}

class AnimalFactory {
public static function create($animalType) {
switch ($animalType) {
case 'dog':
return new Dog();
case 'cat':
return new Cat();
default:
throw new Exception("Animal type not supported");
}
}
}

$animal = AnimalFactory::create('dog');
echo $animal->speak(); // Output: Bark

You might also like