100 companion flashcards · AI-assisted study content · Open the deck →
This deck focuses on PHP programming with an emphasis on object-oriented concepts and modern PHP tooling. The questions walk you through the building blocks of OOP in PHP, including classes, objects, visibility modifiers, inheritance, interfaces, and traits. You will also find cards on namespaces and Composer, which are essential for organizing code and managing dependencies in real-world PHP projects.
It is well suited for learners who already know basic PHP syntax and want to move toward writing more structured, reusable, and maintainable code. Whether you are preparing for a coding interview, working through a backend course, or transitioning from procedural PHP to modern PHP practices, these flashcards offer a focused way to reinforce terminology and core concepts that come up again and again.
Because the deck covers closely related ideas like interfaces versus traits versus inheritance, it helps to study these cards in small sets rather than rushing through them all at once. Try to connect each concept to a short code example you write yourself, since hands-on experimentation makes abstract OOP rules much easier to remember. Spacing your review sessions over several days, rather than cramming, will also help the distinction between similar features, such as traits and interfaces, really stick.
At the heart of modern PHP is its object-oriented programming model. A class is a blueprint that defines the properties (variables) and methods (functions) its objects will have. You create an instance of a class using the new keyword, which also triggers the class's constructor, a special method named __construct() designed to initialize the new object's state. Many modern PHP constructors use promoted parameters, allowing properties to be declared and assigned directly in the constructor signature for more concise code.
Controlling who can access a class's internals is essential for writing maintainable code. PHP provides three access modifiers: public members are accessible from anywhere, protected members are accessible within the class itself and any subclasses that inherit from it, and private members are restricted to the defining class alone. These modifiers let you hide implementation details behind a clean public interface, which is a core principle of encapsulation.
Beyond instance-level data, PHP lets you define static properties and methods that belong to the class as a whole rather than to any particular object. Static members are accessed through the class name, such as Counter::$count, and are useful for shared counters, configuration values, or utility helpers that do not depend on per-instance state. The self keyword inside a static method refers to the same class, providing a way to reference static properties without resorting to the fully qualified name.
PHP supports inheritance through the extends keyword, which lets a child class reuse and extend the behavior of a parent class. The child inherits all public and protected properties and methods, and it can override them to specialize its behavior. This single-inheritance model is simple but limits a class to a single parent, which is why PHP offers complementary mechanisms for sharing code and contracts.
An interface defines a contract that classes promise to fulfill. It lists method signatures without providing their bodies, and any class that uses the implements keyword must supply concrete implementations for every method declared. PHP allows a class to implement multiple interfaces, separated by commas, giving you a form of multiple inheritance for behavior contracts without the ambiguities of inheriting from multiple classes at once. Interfaces are ideal for ensuring that unrelated classes expose a common set of methods, such as a Loggable requirement across various domain objects.
Traits solve a different problem: they let you reuse concrete method implementations across classes that do not share a parent. A trait is declared with the trait keyword and included in a class via the use statement, which mixes its methods into the class body. When two traits used in the same class define a method with the same name, PHP raises a fatal error unless you resolve the conflict explicitly using insteadof (to choose one trait's version) or as (to alias the method under a new name). Traits, interfaces, and inheritance together give PHP a flexible toolkit for code reuse while avoiding the pitfalls of traditional multiple inheritance.
As PHP projects grow, name collisions become inevitable: two libraries may both define a class called User or Logger. Namespaces solve this by acting as virtual directories for your code. Declaring a namespace at the top of a file, such as namespace App\Models;, groups related classes together and prevents unintended clashes with similarly named code elsewhere. Namespaces follow the file structure loosely and provide a hierarchical naming scheme that mirrors modern project organization.
To refer to a namespaced class from another file, you use the use statement, optionally aliasing it with the as keyword to make code more readable. This works much like importing a symbol into the current namespace so that you can refer to it by its short name instead of its fully qualified path. Aliasing is particularly helpful when dealing with long names or when importing two classes that would otherwise share a short name within the same file.
Outside the standard library, PHP relies on Composer as its de facto dependency manager. You declare your project's dependencies in a composer.json file, and running composer require vendor/package both installs the package and records it under the require section. Composer also generates an autoloader in vendor/autoload.php that you include once at the entry point of your application. This autoloader supports PSR-4, PSR-0, classmap, and files-based autoloading, so classes are loaded on demand without manual require statements. A composer.lock file locks the exact versions installed, ensuring reproducible builds across environments and machines.
Since PHP 7, type declarations have become a cornerstone of robust PHP code. Type hints let you declare the expected types of function parameters and return values, enabling PHP's runtime to catch mismatches before they cause subtle bugs. For instance, declaring a function that accepts two int parameters and returns an int ensures that the caller respects the contract. When types do not match, PHP throws a TypeError rather than silently coercing the data.
By default PHP operates in coercive mode, attempting to convert values into the expected type whenever possible. You can opt into stricter behavior by placing declare(strict_types=1); at the top of a file, which forces PHP to throw a TypeError on any type mismatch without attempting coercion. Strict mode is widely recommended for new projects because it eliminates ambiguity and surfaces bugs earlier in the development cycle.
PHP 8 expanded the type system further. Union types let you declare that a parameter or return value may be one of several listed types, written as TypeA|TypeB. This is useful when a function legitimately accepts multiple input forms, such as a string or integer that both can be processed. Closely related is the nullable type syntax, where prefixing a type with a question mark, as in ?User, indicates that the value may be the specified type or null. Together, these features allow you to express precise contracts at the boundary between components, catching misuse while still accommodating realistic data shapes.
PHP's array is a versatile ordered map that doubles as a list, and the language provides many built-in functions for transforming and querying them. array_map() applies a callback to each element and returns a new array, making it the canonical way to transform collections, often paired with arrow functions such as fn($n) => $n * 2. For combining arrays, you can use array_merge(), which re-indexes numeric keys, or the spread operator [...$a, ...$b] introduced in PHP 7.4, which performs the same job inline. With string keys, both approaches let later values overwrite earlier ones.
Filtering and reduction are equally important. array_filter() returns elements for which the supplied callback returns true, and when called without a callback it removes any value considered falsy. array_reduce() collapses an array to a single value by feeding each element through a callback that updates a running carry, perfect for summing numbers, building a string, or accumulating complex state. When you need to check membership, in_array() searches for a value while array_key_exists() searches for a key, and you can pass true as in_array's third argument to compare values strictly with the same rules as the === operator.
String manipulation is just as central. explode() splits a string into an array around a delimiter, and implode() does the inverse, joining array elements into a string with a chosen glue. PHP 8 introduced three highly readable helpers: str_contains() checks for a substring, str_starts_with() checks a prefix, and str_ends_with() checks a suffix, all returning booleans. For formatted output, sprintf() returns a string built from placeholders such as %s for strings, %d for integers, and %f for floats, allowing precise control over the final text without resorting to concatenation.
For database access, PHP Data Objects (PDO) provides a uniform layer across multiple database engines. You connect by instantiating PDO with a Data Source Name that encodes the driver, host, and database name, along with credentials. Once connected, you should always use prepared statements to execute queries. A prepared statement separates SQL logic from data by binding parameters through placeholders, and the database driver handles escaping automatically, eliminating the most common class of SQL injection vulnerabilities.
PDO offers several fetch modes for reading rows from a result set. PDO::FETCH_ASSOC returns each row as an associative array keyed by column name, PDO::FETCH_OBJ returns each row as a stdClass object, and PDO::FETCH_CLASS maps each row onto an instance of a specified class. PDO::FETCH_NUM provides numeric-indexed arrays. You can set a default fetch mode globally so that every fetch call respects it without repetition.
Beyond databases, PHP provides several mechanisms for managing state and handling errors. Sessions let you persist data across requests by storing it server-side, identified by a cookie that holds only a session ID; you start a session with session_start() and read or write the $_SESSION superglobal. Cookies are pure client-side storage created with setcookie() before any output, useful for preferences but less secure for sensitive data. To shut a session down cleanly, you call session_unset() to clear variables and session_destroy() to discard the server-side store, optionally deleting the session cookie as well. Errors and exceptions are managed with try-catch-finally blocks, where finally always runs even when an exception propagates. PHP distinguishes between Exception, which represents recoverable conditions, and Error, which usually signals bugs such as TypeError or ParseError; both implement the Throwable interface. You can create custom exceptions by extending the Exception class, and you can convert traditional PHP warnings into exceptions by registering a callback with set_error_handler() that throws an ErrorException.
Closures are anonymous functions that you can assign to variables, pass as arguments, or return from other functions. A regular closure captures variables from its enclosing scope through the use clause, and by default those variables are copied; prefixing them with an ampersand passes them by reference so the closure can mutate the original. Arrow functions, introduced in PHP 7.4, offer a more concise alternative: written as fn($x) => $x * 2, they automatically capture surrounding variables by value and must contain only a single expression, making them ideal for short transformations like those passed to array_map().
Generators provide a memory-efficient way to work with large or infinite sequences. A generator is simply a function that uses the yield keyword instead of return, emitting one value at a time and pausing execution between yields until the caller asks for the next item. You consume a generator with a foreach loop, which handles the iteration implicitly, or manually by calling current() and next() on the generator object itself. Generators implement the Iterator interface, and because they compute values lazily, they avoid holding entire datasets in memory. You can also yield key-value pairs with the syntax yield $key => $value; to produce associative results.
PHP offers a set of magic methods that hook into the language's built-in behaviors. __toString() runs when an object is used in a string context, allowing you to define how it should be represented. __get() and __set() intercept reads and writes to inaccessible properties, enabling property overloading for things like dynamic configuration objects. __invoke() lets an object be called like a function, treating an instance as a callable. Finally, __destruct() runs when an object is destroyed or goes out of scope, providing a hook for cleanup tasks such as closing file handles, although relying on it for critical logic is discouraged because destruction timing is not guaranteed. Together, these magic methods, combined with closures, generators, and static class members, give PHP developers a rich toolkit for building expressive and efficient applications.
class User { public string $name; }namespace App\Models;array_merge($a, $b) merges arrays, re-indexing numeric keys.[...$a, ...$b] (PHP 7.4+) does the same inline.PDO::FETCH_ASSOC – associative arrayPDO::FETCH_OBJ – anonymous objectPDO::FETCH_CLASS – maps to a classPDO::FETCH_NUM – numeric indexed array$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);fn($x) => $x * 2.use needed) and can only contain a single expression. Regular closures support multiple statements.$arr = ['a', 'b', 'c'] (indexed) and $assoc = ['name' => 'Alice', 'age' => 30] (associative).match expression (PHP 8.0+) is a more powerful alternative to switch. It returns a value, uses strict comparison (===), and supports multiple conditions: $result = match($value) { 1, 2 => 'low', 3 => 'medium', default => 'high' }.password_verify($password, $hash) checks if the password matches the hash generated by password_hash(). It extracts and uses the salt from the hash automatically. Returns bool. This is the secure way to authenticate users.ob_start(), ob_get_clean()) captures script output before sending it to the browser. This allows modifying response headers after HTML output and compressing output. Nested buffers are supported.Drill this topic
100 flashcards on Php Programming — free, no signup needed to start.
Study Php Programming flashcardsLearnWiki pages are generated with AI assistance from LearnCoachAssist's reviewed study catalog and may contain errors — verify anything critical against your course materials.