Title: Php Programming — LearnCoachAssist

Q: What is a class in PHP OOP?
A: A class is a blueprint for creating objects. It defines properties (variables) and methods (functions) that the objects will have.
class User { public string $name; }

Q: What is the difference between public, protected, and private visibility in PHP?
A: public – accessible from anywhere.
protected – accessible within the class and its subclasses.
private – accessible only within the defining class.
These are known as access modifiers.

Q: How do you create an object from a class in PHP?
A: Use the new keyword:
$user = new User();
This calls the class constructor (__construct) if one is defined.

Q: What is the purpose of the __construct() magic method?
A: __construct() is the constructor that runs automatically when an object is created with new.
public function __construct(public string $name) {}
It initializes object properties.

Q: What is inheritance in PHP?
A: Inheritance lets a child class extend a parent class using the extends keyword.
class Admin extends User {}
The child inherits all public and protected properties and methods.

Q: What is an interface in PHP?
A: An interface defines a contract of methods a class must implement, without providing the method bodies.
interface Loggable { public function log(): void; }
A class uses implements to adopt it.

Q: Can a PHP class implement multiple interfaces?
A: Yes. A class can implement multiple interfaces separated by commas:
class Report implements Printable, Exportable { }
This provides a form of multiple inheritance for contracts.

Q: What is a trait in PHP?
A: A trait is a mechanism for code reuse in single-inheritance languages. It groups methods that can be included in multiple classes.
trait Timestampable { public function now() { return time(); } }

Q: How do you use a trait inside a class?
A: Use the use keyword inside the class body:
class Post { use Timestampable; }
The class then gains all methods defined in the trait.

Q: What happens when two traits define a method with the same name?
A: A fatal error occurs unless you resolve the conflict using insteadof or as:
use TraitA, TraitB { TraitA::log insteadof TraitB; }

Q: What are namespaces in PHP?
A: Namespaces organize code and prevent name collisions between classes, functions, and constants.
namespace App\Models;
They act like virtual directories for your code.

Q: How do you import a namespaced class in PHP?
A: Use the use statement at the top of the file:
use App\Models\User;
You can also alias it: use App\Models\User as AppUser;

Q: What is Composer in PHP?
A: Composer is PHP's dependency manager. It handles installing, updating, and autoloading third-party packages.
Configuration lives in composer.json; lock file is composer.lock.

Q: What does composer require do?
A: composer require vendor/package installs a package and adds it to composer.json under the require section.
It also updates composer.lock.

Q: How does Composer autoloading work?
A: Composer generates an autoloader in vendor/autoload.php. Include it once:
require __DIR__ . '/vendor/autoload.php';
It supports PSR-4, PSR-0, classmap, and files autoloading.

Q: What are type hints in PHP?
A: Type hints (type declarations) enforce parameter and return types at runtime:
function add(int $a, int $b): int { return $a + $b; }
Available since PHP 7, expanded in PHP 8.

Q: What is the difference between strict_types and coercive mode?
A: By default PHP uses coercive mode (auto-casts values). Adding declare(strict_types=1); at the top of a file enables strict mode, which throws a TypeError on type mismatches.

Q: What are union types in PHP?
A: Introduced in PHP 8.0, union types allow a parameter or return to accept multiple types:
function parse(string|int $value): string|false { }

Q: What is the nullable type syntax in PHP?
A: Prefix the type with ? to allow null:
function find(int $id): ?User { }
This means the function can return a User object or null.

Q: What is the array_map() function?
A: array_map() applies a callback to each element and returns a new array:
$squares = array_map(fn($n) => $n ** 2, [1, 2, 3]);
Result: [1, 4, 9]

Q: What is the difference between array_merge() and the spread operator for arrays?
A: array_merge($a, $b) merges arrays, re-indexing numeric keys.
The spread operator [...$a, ...$b] (PHP 7.4+) does the same inline.
For string keys, later values overwrite earlier ones.

Q: How does array_filter() work in PHP?
A: array_filter() returns elements for which the callback returns true:
$even = array_filter([1,2,3,4], fn($n) => $n % 2 === 0);
Without a callback, it removes falsy values.

Q: What does array_reduce() do?
A: array_reduce() iteratively reduces an array to a single value using a callback:
$sum = array_reduce([1,2,3], fn($carry, $item) => $carry + $item, 0);
Result: 6

Q: What is the difference between in_array() and array_key_exists()?
A: in_array($needle, $haystack) checks if a value exists in an array.
array_key_exists($key, $array) checks if a key exists.
Use the third parameter true in in_array for strict comparison.

Q: What does the explode() function do?
A: explode() splits a string into an array by a delimiter:
$parts = explode(',', 'a,b,c');
Result: ['a', 'b', 'c']

Q: What does the implode() function do?
A: implode() joins array elements into a string with a glue separator:
echo implode('-', ['2024', '01', '15']);
Result: 2024-01-15

Q: How do str_contains(), str_starts_with(), and str_ends_with() work?
A: Introduced in PHP 8.0, these return bool:
- str_contains('hello world', 'world') → true
- str_starts_with('hello', 'he') → true
- str_ends_with('hello', 'lo') → true

Q: What is sprintf() used for in PHP?
A: sprintf() returns a formatted string using placeholders:
$msg = sprintf('Hello %s, you are %d years old', 'Alice', 30);
Common specifiers: %s (string), %d (integer), %f (float).

Q: What is PDO in PHP?
A: PDO (PHP Data Objects) is a database abstraction layer providing a uniform interface for accessing databases like MySQL, PostgreSQL, and SQLite.
$pdo = new PDO('mysql:host=localhost;dbname=app', 'user', 'pass');

Q: How do prepared statements prevent SQL injection in PDO?
A: Prepared statements separate SQL logic from data. Placeholders are bound safely:
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(['id' => $userId]);
The database driver escapes input automatically.

Q: What PDO fetch modes are commonly used?
A: - PDO::FETCH_ASSOC – associative array
- PDO::FETCH_OBJ – anonymous object
- PDO::FETCH_CLASS – maps to a class
- PDO::FETCH_NUM – numeric indexed array
Set default: $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

Q: How do you start and use sessions in PHP?
A: Call session_start(); at the top of your script.
Store data: $_SESSION['user'] = 'Alice';
Read data: echo $_SESSION['user'];
Sessions persist data across requests using a server-side store and a session cookie.

Q: How do you destroy a session in PHP?
A: To fully destroy a session:
session_unset(); — clears all session variables.
session_destroy(); — destroys the session data on the server.
Also delete the session cookie with setcookie(session_name(), '', time() - 3600);

Q: How do you set a cookie in PHP?
A: Use setcookie() before any output:
setcookie('theme', 'dark', time() + 86400, '/');
Parameters: name, value, expiry timestamp, path. Read it back with $_COOKIE['theme'].

Q: What is the difference between sessions and cookies?
A: Sessions store data on the server (identified by a cookie holding the session ID).
Cookies store data on the client browser.
Sessions are more secure for sensitive data; cookies persist after the browser closes if given an expiry.

Q: What is try-catch-finally in PHP?
A: try wraps code that might throw an exception. catch handles it. finally always runs:
try { riskyOperation(); } catch (Exception $e) { log($e->getMessage()); } finally { cleanup(); }

Q: What is the difference between Exception and Error in PHP?
A: Both implement Throwable.
Exception – recoverable conditions your code should handle.
Error – serious problems like TypeError or ParseError usually indicating bugs.
Catch both with catch (Throwable $t).

Q: How do you create a custom exception in PHP?
A: Extend the Exception class:
class InsufficientFundsException extends Exception {
  public function __construct(public float $amount) {
    parent::__construct("Insufficient funds: $amount");
  }
}

Q: What does set_error_handler() do?
A: set_error_handler() registers a custom callback to handle PHP warnings and notices instead of the default handler:
set_error_handler(function($errno, $errstr) { throw new ErrorException($errstr, $errno); });

Q: What is a closure in PHP?
A: A closure is an anonymous function that can capture variables from its surrounding scope using use:
$greet = function($name) use ($prefix) { return "$prefix $name"; };

Q: What is the difference between a closure and an arrow function?
A: Arrow functions (PHP 7.4+) are short closures: fn($x) => $x * 2.
They auto-capture variables by value (no use needed) and can only contain a single expression. Regular closures support multiple statements.

Q: How do you pass a variable by reference into a closure?
A: Use & in the use clause:
$count = 0;
$inc = function() use (&$count) { $count++; };
$inc();
Now $count is 1. Without &, the closure gets a copy.

Q: What is a generator in PHP?
A: A generator is a function that uses yield to produce values one at a time, pausing between each:
function numbers() { for ($i = 0; $i < 5; $i++) { yield $i; } }
Generators are memory-efficient for large datasets.

Q: How do you consume a generator in PHP?
A: Use a foreach loop:
foreach (numbers() as $n) { echo $n; }
Or manually with $gen = numbers(); $gen->current(); $gen->next();
Generators implement the Iterator interface.

Q: What is the yield keyword used for?
A: yield pauses the generator and returns a value to the caller. Execution resumes on the next iteration:
function abc() { yield 'a'; yield 'b'; yield 'c'; }
You can also yield key-value pairs: yield $key => $value;

Q: What does the __toString() magic method do?
A: __toString() is called when an object is used in a string context:
class Money { public function __toString(): string { return "$this->amount $this->currency"; } }
echo new Money(10, 'USD'); outputs 10 USD.

Q: What are __get() and __set() magic methods?
A: __get($name) is called when reading an inaccessible property.
__set($name, $value) is called when writing to one.
They enable property overloading:
public function __get($name) { return $this->data[$name] ?? null; }

Q: What does the __invoke() magic method do?
A: __invoke() is called when you try to call an object as a function:
class Multiplier { public function __invoke(int $n): int { return $n * 2; } }
$double = new Multiplier(); echo $double(5); outputs 10.

Q: What is the __destruct() magic method?
A: __destruct() is called when an object is destroyed or goes out of scope. Used for cleanup tasks:
public function __destruct() { fclose($this->fileHandle); }
It runs automatically; avoid relying on it for critical logic.

Q: What is the static keyword used for in PHP classes?
A: static declares properties or methods that belong to the class itself, not to instances:
class Counter { public static int $count = 0; public static function increment(): void { self::$count++; } }
Access via Counter::$count.