PHP Interview Questions and Answers

author image Hirely
at 06 Jan, 2025

Question: What is late static binding in PHP?

Answer:

Late Static Binding (LSB) is a feature introduced in PHP 5.3 that allows you to refer to the called class in a context of static inheritance. It enables you to call static methods from a child class, even when the method is defined in a parent class, using the child class’s context instead of the parent’s context.

Before PHP 5.3, when dealing with static methods in inherited classes, the static keyword always referred to the class where the method was originally defined, not the class that was actually calling it. Late Static Binding solves this issue by allowing you to bind the class in which the method is actually being called.

Key Concepts:

  • Static Binding: Refers to the behavior where a static method is called on a class, and PHP determines which method to use based on the class where the static method is defined.

  • Late Static Binding: Allows a static method in a parent class to behave differently depending on the class that calls it, which is particularly useful for static methods in a class hierarchy.

Syntax:

To use Late Static Binding, PHP provides the static keyword, which can be used inside a class method to refer to the class that is actually calling the method, rather than the class where the method is defined.

The static:: syntax is used to access static methods or properties in the context of the called class, rather than the class where the method is defined.

Example:

class ParentClass {
    public static function whoCalledMe() {
        // This refers to the class that called the method, not the class where it's defined
        echo "Called by: " . static::class;
    }
}

class ChildClass extends ParentClass {
    // Inherits the whoCalledMe() method from ParentClass
}

// Calling the method from the child class context
ChildClass::whoCalledMe(); // Output: Called by: ChildClass

Breakdown of the Example:

  • The whoCalledMe() method is defined in ParentClass, but when it is called by ChildClass, the static::class will return the name of the calling class (ChildClass), not ParentClass.
  • Without late static binding, the method would have returned ParentClass, because that’s where the method was originally defined. But with static::, it refers to the class in which the method was actually called.

Use Case:

Late Static Binding is particularly useful when you are creating base classes that need to be extended, and the base class should be flexible enough to allow for dynamic behavior in child classes. It is commonly used in patterns like Factory Methods, Singleton, or ORM (Object-Relational Mapping).

Example:

Here’s a more practical example showing how LSB can be used in a factory method pattern:

class Base {
    protected static $instances = [];

    // The factory method to create an instance
    public static function getInstance() {
        // Create a new instance if it doesn't exist
        if (!isset(self::$instances[static::class])) {
            self::$instances[static::class] = new static();
        }

        return self::$instances[static::class];
    }
}

class Child extends Base {
    // Some additional functionality
}

$childInstance = Child::getInstance(); // This will create an instance of Child, not Base

var_dump($childInstance instanceof Child); // Output: bool(true)

Explanation of Example:

  • The getInstance() method is defined in the Base class, but it creates an instance of the class that calls it (thanks to static::class), which in this case is Child.
  • Without Late Static Binding, calling Base::getInstance() would have always returned an instance of Base. With LSB, it returns an instance of Child.

Benefits of Late Static Binding:

  1. Flexibility: Allows methods in a parent class to interact with the class that calls them, making them more flexible in the context of inheritance.
  2. Clean Code: Helps avoid duplication of code in child classes by allowing parent classes to define common logic for child classes.
  3. Improved Factory Patterns: Useful in factory design patterns to instantiate the correct class dynamically based on context.

Summary:

Late Static Binding (LSB) in PHP provides a way to bind static methods to the calling class at runtime, rather than the class where the method is originally defined. This allows for more flexible and dynamic class behavior, especially when working with inheritance. It is useful for patterns that need to work with different child classes while keeping the logic in the parent class.

Question: What are cookies in PHP?

Answer:

Cookies in PHP are small pieces of data that are stored on the client’s browser and sent to the server with each HTTP request. They are used to store user-specific information, such as preferences, login credentials, session data, and other information that needs to persist across different pages and sessions.

Cookies are set by the server (or PHP script) and are automatically sent back to the server with each request from the client (browser). They are stored on the user’s computer and can be accessed by both the server and the client-side code.

Key Characteristics of Cookies:

  1. Client-Side Storage: Cookies are stored on the client (browser), not the server.
  2. Expiration: Cookies can have an expiration time. They can either be session cookies (which are deleted when the browser is closed) or persistent cookies (which remain until a specified expiration date).
  3. Automatic Sending: Every time the client makes a request to the same server, the browser sends the cookie data along with the request, which the server can use to identify the user.

Creating and Setting Cookies in PHP:

To create or set a cookie in PHP, the setcookie() function is used. The syntax for setting a cookie is:

setcookie(name, value, expire, path, domain, secure, httponly);
  • name: The name of the cookie.
  • value: The value of the cookie.
  • expire: The expiration time of the cookie (in UNIX timestamp format). If omitted or set to 0, the cookie is a session cookie and will be deleted when the browser is closed.
  • path: The path within the domain where the cookie is available. Default is the entire domain.
  • domain: The domain that the cookie is available to. By default, it’s the domain of the page that set the cookie.
  • secure: If true, the cookie will only be sent over secure HTTPS connections.
  • httponly: If true, the cookie will be accessible only through the HTTP protocol (not JavaScript).
<?php
// Set a cookie that expires in 1 hour
setcookie("user", "JohnDoe", time() + 3600, "/");  // 3600 = 1 hour

// Check if the cookie is set
if (isset($_COOKIE["user"])) {
    echo "Welcome " . $_COOKIE["user"];
} else {
    echo "Cookie is not set!";
}
?>
  • The above code sets a cookie named user with the value JohnDoe. The cookie will expire in 1 hour.
  • After setting the cookie, we check if the cookie exists using isset() and display a message accordingly.

Retrieving Cookies:

Once a cookie has been set, you can retrieve its value using the $_COOKIE superglobal array.

<?php
if (isset($_COOKIE["user"])) {
    echo "User: " . $_COOKIE["user"];  // Outputs: User: JohnDoe
} else {
    echo "No user cookie set!";
}
?>

Deleting Cookies:

To delete a cookie, you need to set its expiration time to a past time (usually a timestamp before the current time). This will instruct the browser to remove the cookie.

<?php
// Set a cookie with an expiration date in the past to delete it
setcookie("user", "", time() - 3600, "/");  // Expire 1 hour ago

// Check if the cookie is deleted
if (isset($_COOKIE["user"])) {
    echo "User: " . $_COOKIE["user"];
} else {
    echo "Cookie has been deleted!";
}
?>

Important Points:

  1. Cookies and Security:
    • Secure cookies (with secure set to true) are only sent over HTTPS connections.
    • HTTPOnly cookies cannot be accessed via JavaScript, reducing the risk of client-side script attacks.
  2. Cookie Size Limitation: Cookies are small (typically 4KB in size), so they should not be used for storing large amounts of data.
  3. Sending Cookies: Cookies must be sent before any output is generated (i.e., no HTML, whitespace, or text can be sent before calling setcookie()), as cookies are part of the HTTP headers.

Use Cases for Cookies in PHP:

  1. User Authentication: Storing a user’s login session information to remember them across multiple page requests.
  2. User Preferences: Storing user settings such as language, theme, and display options.
  3. Tracking and Analytics: Keeping track of user behavior, such as which pages are visited or for storing cart information in e-commerce sites.
  4. Persistent Sessions: Saving session data across browser sessions, making it possible to persist user data even after closing and reopening the browser.

Summary:

Cookies in PHP are used for storing small amounts of data on the client’s browser that can be sent back to the server with every HTTP request. They are commonly used for tasks like user authentication, tracking user preferences, and maintaining session information. You can create cookies using the setcookie() function and access them through the $_COOKIE superglobal.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as PHP interview questions, PHP interview experiences, and details about various PHP job positions. Click here to check it out.

Related Posts

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now