PHP Functions


PHP Functions Interview with follow-up questions

1. What is a function in PHP and why are they used?

A function in PHP is a named, reusable block of code that performs a specific task. Functions are defined with the function keyword, can accept parameters, and optionally return a value.

function greet(string $name): string {
    return "Hello, $name!";
}

echo greet('Alice'); // "Hello, Alice!"

Why functions are used:

  • Reusability: Write logic once, call it many times — avoid repeating code.
  • Separation of concerns: Each function does one thing, making code easier to read and test.
  • Testability: Isolated functions are easy to unit test.
  • Maintainability: Fixing a bug in a function fixes it everywhere it is called.

Modern PHP function features:

  • Type declarations on parameters and return values (string $name, : string) — enforced at runtime when strict_types=1 is declared.
  • Default parameter values: function greet(string $name = 'World'): string
  • Named arguments (PHP 8.0+): greet(name: 'Bob')
  • First-class callable syntax (PHP 8.1+): $fn = greet(...) creates a Closure from a function reference — replaces Closure::fromCallable('greet').
  • Arrow functions for short closures: $double = fn($n) => $n * 2;
↑ Back to top

Follow-up 1

Can you provide an example of a PHP function?

Sure! Here's an example of a PHP function that calculates the sum of two numbers:

function sum($num1, $num2) {
    return $num1 + $num2;
}

$result = sum(5, 3);
echo $result; // Output: 8

In this example, the sum() function takes two parameters ($num1 and $num2), adds them together, and returns the result.

Follow-up 2

What is the syntax for creating a function in PHP?

The syntax for creating a function in PHP is as follows:

function functionName(parameter1, parameter2, ...) {
    // Function body
    // Code to be executed
    // Return statement (optional)
}
  • function keyword is used to define a function.
  • functionName is the name of the function.
  • parameter1, parameter2, ... are the optional parameters that the function can accept.
  • The function body contains the code to be executed when the function is called.
  • The return statement is used to return a value from the function (optional).

Follow-up 3

How do you call a function in PHP?

To call a function in PHP, you simply need to use its name followed by parentheses. If the function accepts parameters, you can pass the values inside the parentheses.

Here's an example:

function sayHello($name) {
    echo 'Hello, ' . $name . '!';
}

sayHello('John'); // Output: Hello, John!

In this example, the sayHello() function is called with the parameter 'John'.

Follow-up 4

What is the difference between built-in and user-defined functions in PHP?

The difference between built-in and user-defined functions in PHP is as follows:

  • Built-in functions: These are functions that are already provided by PHP and can be used directly without any additional setup. Examples of built-in functions in PHP include strlen(), array_push(), and date(). They are part of the PHP core and are available for use in any PHP script.

  • User-defined functions: These are functions that are created by the user to perform specific tasks. They are defined using the function keyword and can be customized to suit the user's requirements. User-defined functions provide flexibility and allow developers to create their own reusable code blocks.

2. What are the different types of functions in PHP?

PHP functions fall into several categories:

1. Built-in functions PHP ships with thousands of built-in functions covering strings (strlen, str_contains, mb_strtolower), arrays (array_map, array_filter, array_find), math, dates, file I/O, and more. No import needed.

2. User-defined functions Defined by the developer with function:

function calculateTax(float $amount, float $rate = 0.2): float {
    return $amount * $rate;
}

3. Anonymous functions (closures) Functions without a name, assignable to variables and passable as arguments. Can capture outer-scope variables with use:

$multiplier = 3;
$triple = function (int $n) use ($multiplier): int {
    return $n * $multiplier;
};

4. Arrow functions (PHP 7.4+) Concise single-expression closures that automatically capture outer scope by value:

$triple = fn(int $n): int => $n * 3;
$result = array_map(fn($n) => $n * 2, [1, 2, 3]);

5. Recursive functions Functions that call themselves:

function factorial(int $n): int {
    return $n <= 1 ? 1 : $n * factorial($n - 1);
}

6. Variadic functions Accept a variable number of arguments with ...:

function sum(int ...$numbers): int {
    return array_sum($numbers);
}
sum(1, 2, 3, 4); // 10

7. First-class callables (PHP 8.1+) Any callable can be converted to a Closure using ... syntax: $fn = strlen(...).

↑ Back to top

Follow-up 1

What is an anonymous function in PHP?

An anonymous function in PHP, also known as a closure, is a function that does not have a name. It can be assigned to a variable or passed as an argument to other functions. Anonymous functions are useful when you need to create a function on the fly without defining it separately. Here's an example of an anonymous function in PHP:

$greet = function($name) {
    echo 'Hello, ' . $name;
};

$greet('John'); // Output: Hello, John

Follow-up 2

What is a recursive function in PHP?

A recursive function in PHP is a function that calls itself within its own definition. This allows the function to solve problems that can be broken down into smaller sub-problems. Recursive functions are commonly used in tasks such as traversing tree structures, calculating factorials, and implementing sorting algorithms. Here's an example of a recursive function in PHP that calculates the factorial of a number:

function factorial($n) {
    if ($n <= 1) {
        return 1;
    }
    return $n * factorial($n - 1);
}

echo factorial(5); // Output: 120

Follow-up 3

Can you provide an example of a built-in function in PHP?

Sure! Here's an example of a built-in function in PHP:

$str = 'Hello, World!';
echo strlen($str); // Output: 13

Follow-up 4

What is a callback function in PHP?

A callback function in PHP is a function that is passed as an argument to another function and is called by that function at a specific point in its execution. Callback functions are commonly used in scenarios where you want to customize the behavior of a function without modifying its code. They are often used in combination with higher-order functions, such as array_map() and usort(). Here's an example of a callback function in PHP:

function square($n) {
    return $n * $n;
}

$numbers = [1, 2, 3, 4, 5];
$squaredNumbers = array_map('square', $numbers);

print_r($squaredNumbers); // Output: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )

3. What is a variable function in PHP?

A variable function uses a string variable to call a function dynamically — PHP looks up the function named by the variable's value and calls it.

function sayHello(): void {
    echo "Hello!";
}

$func = 'sayHello';
$func(); // calls sayHello() — outputs "Hello!"

With arguments:

function add(int $a, int $b): int {
    return $a + $b;
}

$operation = 'add';
echo $operation(3, 4); // 7

Variable methods on objects:

class Formatter {
    public function upper(string $s): string { return strtoupper($s); }
    public function lower(string $s): string { return strtolower($s); }
}

$method = 'upper';
$formatter = new Formatter();
echo $formatter->$method('hello'); // "HELLO"

PHP 8.1 first-class callable syntax (modern replacement): Rather than storing function names as strings, store actual Closure references:

$fn = strlen(...);  // equivalent to Closure::fromCallable('strlen')
echo $fn('hello');  // 5

This is type-safe, works with static analysis tools, and supports IDE auto-complete — variable functions using strings do not.

Interview note: Variable functions using string names are hard to statically analyze (PHPStan/Psalm cannot know what type they return). First-class callables are the modern, type-safe alternative.

↑ Back to top

Follow-up 1

How do you declare a variable function in PHP?

To declare a variable function in PHP, you simply assign a function to a variable. Here's an example:

$myFunction = function() {
    echo 'Hello, World!';
};

In this example, the anonymous function is assigned to the variable $myFunction.

Follow-up 2

Can you provide an example of a variable function?

Sure! Here's an example of a variable function in PHP:

$myFunction = function($name) {
    echo 'Hello, ' . $name . '!';
};

$myFunction('John'); // Output: Hello, John!
$myFunction('Jane'); // Output: Hello, Jane!

In this example, the variable function $myFunction takes a parameter $name and echoes a personalized greeting.

Follow-up 3

What is the use of variable functions in PHP?

Variable functions in PHP have several uses:

  1. Callbacks: Variable functions can be used as callbacks for functions like array_map() or usort(), allowing you to define custom logic on the fly.
  2. Dynamic function calls: You can use variable functions to dynamically call different functions based on certain conditions or user input.
  3. Higher-order functions: Variable functions enable you to create higher-order functions that accept other functions as arguments or return functions as results.

These are just a few examples of the use cases for variable functions in PHP.

Follow-up 4

What are the limitations of variable functions in PHP?

While variable functions in PHP provide flexibility, there are some limitations to be aware of:

  1. Scope: Variable functions are subject to the same scope rules as regular functions. They can only access variables within their own scope or variables passed as arguments.
  2. Performance: Variable functions can be slower than regular function calls due to the additional overhead of variable lookup and dynamic dispatch.
  3. Debugging: Variable functions can make code harder to debug and understand, especially when used excessively or in complex scenarios.

It's important to use variable functions judiciously and consider the trade-offs in terms of code readability and performance.

4. What is the difference between include() and require() function in PHP?

Both include and require execute the specified PHP file at that point in the script. The difference is in error handling when the file cannot be found:

Statement File not found behavior
include Emits E_WARNING, script continues
require Emits E_COMPILE_ERROR, script halts
include 'sidebar.php';  // missing → warning, page still loads
require 'config.php';   // missing → fatal error, page cannot load

include_once and require_once prevent a file from being included more than once — useful when a file defines functions or classes that would cause a redeclaration error if loaded twice.

When to use which:

  • Use require / require_once for critical dependencies (configuration files, database connections, core class definitions) where the application cannot function without the file.
  • Use include / include_once for optional components (sidebar widgets, optional feature modules) where the application can reasonably continue without them.

Modern practice — Composer autoloading: In contemporary PHP projects, manually writing require_once for every class is replaced by PSR-4 autoloading. You simply run composer dump-autoload and require_once 'vendor/autoload.php' once; Composer then loads any class file on demand. Knowing this distinction remains important for understanding legacy code and for PHP fundamentals questions.

↑ Back to top

Follow-up 1

What happens if the file is not found with include()?

If the file is not found with include(), a warning will be issued and the script will continue to execute. This means that the rest of the code will be executed even if the included file is not found. It is important to handle this warning properly to avoid unexpected behavior in your script.

Follow-up 2

What happens if the file is not found with require()?

If the file is not found with require(), a fatal error will be issued and the script will stop executing. This means that the rest of the code will not be executed if the required file is not found. It is important to make sure that the required file exists to avoid any fatal errors in your script.

Follow-up 3

Can you provide an example of when to use include() and require()?

Sure! Here's an example:

Suppose you have a PHP file called 'functions.php' that contains some useful functions. You can use include() or require() to include this file in another PHP file, like this:

// Using include()
include('functions.php');

// Using require()
require('functions.php');

Both include() and require() will include and evaluate the 'functions.php' file, making the functions defined in that file available in the current PHP file. The difference is in how they handle errors, as explained earlier.

Follow-up 4

What is the difference between include_once() and require_once()?

The include_once() and require_once() functions are similar to include() and require(), but they have an additional check to ensure that the file is included only once.

If a file has already been included using include_once() or require_once(), it will not be included again. This can be useful in situations where you want to include a file multiple times but only want it to be included once.

The main difference between include_once() and require_once() is how they handle errors when the file is not found. If the file is not found with include_once(), a warning will be issued and the script will continue to execute. On the other hand, if the file is not found with require_once(), a fatal error will be issued and the script will stop executing.

5. What is the purpose of the function setcookie() in PHP?

setcookie() sends an HTTP Set-Cookie header to the client's browser, instructing it to store a cookie that will be sent back in subsequent requests.

setcookie(
    name:     'user_pref',
    value:    'dark_mode',
    expires:  time() + (86400 * 30),  // 30 days
    path:     '/',
    domain:   '.example.com',
    secure:   true,     // HTTPS only
    httponly: true      // not accessible via JavaScript
);

PHP 7.3+ supports an options array form:

setcookie('user_pref', 'dark_mode', [
    'expires'  => time() + 86400 * 30,
    'path'     => '/',
    'domain'   => '.example.com',
    'secure'   => true,
    'httponly' => true,
    'samesite' => 'Lax',   // 'Strict', 'Lax', or 'None'
]);

Key interview points:

  • setcookie() must be called before any output (before any HTML or echo) because it sends HTTP headers. Use output buffering or structure code to keep headers early.
  • The SameSite attribute (Lax or Strict) is essential for CSRF protection.
  • Secure => true ensures the cookie is only transmitted over HTTPS — required for sensitive cookies in production.
  • HttpOnly => true prevents JavaScript access, mitigating cookie theft via XSS.
  • To delete a cookie, set its expiry to a time in the past: setcookie('name', '', time() - 3600).

Access cookies in subsequent requests via $_COOKIE['user_pref'].

↑ Back to top

Follow-up 1

What parameters does setcookie() accept?

The setcookie() function in PHP accepts the following parameters:

  • name: the name of the cookie
  • value: the value of the cookie
  • expire: the expiration time of the cookie (optional)
  • path: the path on the server where the cookie will be available (optional)
  • domain: the domain that the cookie is available to (optional)
  • secure: indicates whether the cookie should only be transmitted over a secure HTTPS connection (optional)
  • httponly: indicates whether the cookie should only be accessible through the HTTP protocol (optional)

Follow-up 2

How do you retrieve a cookie value in PHP?

To retrieve a cookie value in PHP, you can use the $_COOKIE superglobal variable. The $_COOKIE variable is an associative array that contains all the cookies that have been set. You can access a specific cookie value by using its name as the key in the $_COOKIE array. For example, to retrieve the value of a cookie named 'username', you can use $_COOKIE['username'].

Follow-up 3

What is the lifespan of a cookie set by setcookie()?

The lifespan of a cookie set by setcookie() can be controlled by the 'expire' parameter. The 'expire' parameter specifies the expiration time of the cookie in seconds since the Unix epoch. If the 'expire' parameter is not provided, the cookie will expire at the end of the session, meaning it will be deleted when the user closes their browser. If a specific expiration time is set, the cookie will be stored on the user's computer until that time is reached.

Follow-up 4

How do you delete a cookie in PHP?

To delete a cookie in PHP, you can use the setcookie() function with an expiration time in the past. By setting the 'expire' parameter to a time in the past, the browser will delete the cookie. For example, to delete a cookie named 'username', you can use the following code:

setcookie('username', '', time() - 3600);

Live mock interview

Mock interview: PHP Functions

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.