Anki Cards: PHP Core Terminology
PHPCore Terminology (Core📌
AIn web PHP, a single execution ofPHPcode to respond to an HTTP request(orisCLI run) isoften called a {{c1::script}request}} (orascript{{c2::request}})run).- PHP
isrunstypically executed byvia an {{c1::interpreter}} (the{{c2::PHPengine}})engine), notcompiledbyahead-of-timeproducing a native binary like C/C++. - PHP is
a{{c1::server-side}}language:: the browser receives the {{c2::output}} (e.g.,HTML/JSON), notyourthe {{c3::PHP source}}. PHPBuilt-incanarraysrunthatinare always available (e.g.,$_GET,$_POST,$_SERVER) are called {{c1::web server mode}superglobals}}(responding to HTTP) or in {{c2::CLI}} (command line).- PHP’s
executionautomaticmodelconversionisbetweenusuallytypes{{c1::stateless per request}}; to persist data across requests you need {{c2::sessions}}(e.g.,{{c3::cookies}}, or a {{c4::database}}.
Superglobals & HTTP Basics 🌐
declare(strict_types=1); \$q = \$_GET['q'] {{c1::??}} ''Security Essentials (Validation, Sanitization, Escaping) 🛡️
require is {{c1::fatal}} if the file is missing; include emits a {{c2::warning}} and continues.
Composer-style class loading is {{c1::autoloading}}, commonly via {{c2::MyApp\Foo.
{{c1::Dependency injection}} means {{c2::Daily PHP OutputConstructs &(“Commands”) Debugging🧠
Theechomost common way to output text isoutputs {{c1::echo}strings}} (aandlanguagecanconstruct)output multiple args separated by commas).printissimilar tolike echo butitreturns {{c1::returns}1}} (so it’s usable in expressions).
var_dump($x) shows both {{c1::type}} and {{c2::print_r($x, typetrue) die() exit() {{c1::include_once Includes & File Loading 📁
require_once ensure a file is require __DIR__ . '/vendor/autoload.php';Control Flow (ConditionalsIf &/ Switch / Match / Loops) 🔁
Aifstandard(...)conditional{}chainruns only when the condition is {{c1::if}} → {{c2::elseif}} → {{c3::else}true}}.switchrequirestypicallyexplicitneeds{{c1::break}}to avoid{{c2::fall-through}}.through into the next case.match(PHP...)8+){ ... } is an {{c1::expression}} that {{c2::returns a value}}and(unlikeswitch).
match uses {{switch cases can do).
foreach ($arr as $value) iterates over the array’s {{c1::values}}.
foreach most($arr commonas loop$k for=> arrays$v) foreach (\$arr as {{c1::\$k}} =>the {{c2::\$v}value}}) { ... }.
break exits continue skips to the {{c2::next do { ... } while (...); loop runs the body at least {{c1::once}}.
Functions & ScopeOrganization 🧩
- A function can
declaredefine a default parameter likefunction f($x = 123), meaning it’s {{c1::optional}} when calling.
return exits a function and optionally provides a {{c1::value}}.
global $x; accesses a variable from the {{c1::global scope}} (best used {{c2::sparingly}}).
static $x = 0; inside a function persists {{c1::between calls}} during the same request.
A function with a return type : functionint f():promises it will return an {{c1::int}} { ... }function f(\$x = {{c1::123}})staticarray_mapfunction() {}{{c1::fn}strict_types}}(\$x) => ... ErrorsError Handling & Exceptions 🚨🚧
Exception handling usestry { ... } catch (catches both {{c1::Exception}} and many {{c2::Error}} types.{{c1::Throwable}}Throwable\$e) { ... }
finally { ... }{{c1::throw}} new Exception('message');finally runs whether an exception throw new Exception('msg'); {{c1::raises}} an exception to be handled by a caller.
If an exception is not caught, it typically causes a {{c1::fatal error}} and aborts the request.
OOP: Classes, Visibility, Inheritance 🧱
new ClassName() creates an {{c1::object instance}}.
public members are accessible {{c1::everywhere}}; protected inside {{c2::class + subclasses}}; private only inside the {{c3::declaring class}}.
extends means {{c1::inheritance}}; implements means fulfilling an {{c2::interface contract}}.
$this-> accesses the {{c1::current object}} instance members.
self:: refers to the {{c1::current class}}; parent:: refers to the {{c2::parent class}}.
A trait is a mechanism for {{c1::abstract interface Variables, Types, and “Type Juggling”Operators 🧱
- PHP variables start with
the symbola {{c1::$}}.sign. PHPdefine('APP_ENV',supports'dev')“typedefinesjuggling,” meaning it maya {{c1::auto-convert}constant}}typesat runtime;constdefines a constant at {{c2::compile time}} (stringand↔canint,beetc.)used in classes).ToScalarenforce stricter scalar type checking, add{{c1::declare(strict_types=1);}}at the top of a file.
null . is {{c1::.= {{c1::(int)}}\$x{{c2::(string)}}\$x== is {{c1::loose comparison}} (type juggling); === is {{c2::Operators & Comparisons ⚖️
\$full = \$a {{c1::.}} \$b;{{c1::.=}}value).
The <=> returns {{c1::-1}}, {{c2::0}}, or {{c3::1}} for ordering comparisons.
Null coalescing ?? uses the right-hand side only if the left is {{c1::?-> && / || are {{c1::short-circuit}} boolean operators.
The ternary cond is? a : b picks {{c1::condition}a}} ?when cond is true, else {{c2::A}b}} : {{c3::B}}.{{c1::<=>}}Strings (Everyday Tools) 🧵
Single-quotedInstringssingledoquotes'...', variables are generally {{c1::not}not interpolated}}.
"...", variables like $name are {{c1::interpolated}}.
strlen($s) returns the string length in {{c1::bytes}} strpos($haystack, a$needle) === false checks).
trim($s) explode(',', text$s) implode(',', $arr) converts an array into a sprintf("Hi %s", $name) returns a formatted%s%dstrlenArrays (Workhorse Structures)Workhorse) 🧰
An[]creates an {{c1::array}} literal (indexed or associative).
\$a = {{c1::[10, 20, 30]}}; uses numeric {{c1::indexes}}.
['name' {{c1::=>}} 'Ada'] uses string {{c1::keys}}.
$a[] = 99; appends to the {{c1::end}} of an indexed array.
count($arr) returns the number of {{c1::elements}}.
in_array($needle, $haystack, true) uses strict checking when the third argument is {{c1::true}}.
array_key_exists('k', $arr) checks for the presence of a {{c1::key}} even if its value is {{c2::null}}.
array_map(fn($x) => ..., $arr) transforms each element and returns a {{c1::new array}}.
array_filter($arr, $fn) keeps elements where the callback returns {{c1::true}}.
array_reduce($arr, $fn, $initial) folds an array \$a{{c1::[]}}a = 99;sort($arr) sortasort($arr) sorts by {{c1::asort}preserving keys}}.
{{c2::ksort}}ksort($arr) sorts by [$a, $b] = {{c1::$arr}key}};ConstantsHTTP & ConfigurationSuperglobals 🧷🌐
DefineQueryastringglobalparametersconstantarewithread from {{c1::define(‚NAME‘,$_GET}}.
const{{c1::const VERSION}}$q = $_GET['1.0.0'q'] ?? '';header('Location: via .env/path'); intriggers somean frameworks)HTTP {{c1::redirect}}.
After sending a Location header, you should call {{c1::exit}} to stop further output.
http_response_code(404); sets the HTTP status code to {{c1::404}}.
OOPSecurity (Classes,Defaults Visibility, and Keywords) 🏛🛡️
CreateForanHTMLobjectoutput,instancehtmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')prevents {{c1::XSS}} in HTML/text contexts.
ENT_QUOTES escapes both {{c1::single}} and {{c2::double}} quotes.
Passwords should be stored using {{c1::$_GET/$_POST types: always {{c1::validate}} and/or {{c2::cast}} (e.g., new User()(int)).
{{c1::abstract}}{{c1::trait}}{{c1::ClassName::}}member ({{c1::self::}}{{c2::parent::}}Composer & Autoloading ⚙️
Thecomposer.jsondependencydeclaresmanifestdependenciesisand {{c1::autoload rules}}.
composer.json}};lock pins the {{c1::vendor/autoload.php}}.
require standard__DIR__ is. '/vendor/autoload.php'; enables {{c1::DatabasePDO (PDO Fundamentals)Database) 🗄️
PDOInstandsPDO,forsettingPDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTIONmakes DB errors throw {{c1::PHP Data Objects}} and provides a consistent DB interface.
$pdo->{{c1::$pdo->prepare(…prepare}}(...)}} and executed with {{c2::$stmt->execute(…)}}.
$stmt->{{c1:::email}execute}}(['email' => {{c2::$email}}]email]) (named placeholders).
$stmt->fetch(PDO::{{c1::fetch}FETCH_ASSOC}}(PDO::FETCH_ASSOC)).
After an INSERT, $pdo->{{c1::$pdo->lastInsertId(lastInsertId}}()}}. WordPress Parallels (If You Use WP) 🧩
- WordPress
“do something now” hooksactions are registered with {{c1::actions}} added via {{c2::add_action}}.
esc_html, esc_attr, {{sanitize_text_field and {{wp_nonce_field, check_admin_referer).
$wpdb->prepare(...) is the WordPress “QuickI Gotchas”Forget ThatThis” SaveReminders Hours ⏱🗂️
AvoidPrefershorttheopenfulltagsopening<?—prefertag {{c1::<?php}}for(avoidportability.short tags).AfterInsendingpureaPHPredirectfiles,header,it’salwayscommon to omit the closing tag?>to avoid accidental {{c1::exit;whitespace output}}.
'0' is {{c1::falsy}} Extra High-Value Additions (Fits the Topic) ✨
error_reporting(E_ALL); and ini_set('display_errors', '1'); are useful in {{c1::development}} (but not in production).
Prefer filter_input(INPUT_GET, 'q', FILTER_SANITIZE_SPECIAL_CHARS) for simple input handling, but still {{c1::validate}} properly.
json_encode($data, JSON_UNESCAPED_UNICODE) produces {{c1::JSON}} output; set header Content-Type: application/json.
To read JSON request bodies: $raw = file_get_contents('php://input'); $data = json_decode($raw, true);—true yields an {{c1::associative array}}.
isset($x) is false if $x is {{c1::not set}} or {{c2::null}}.
empty($x) treats values like 0, '0', [], and null as {{c1::empty}} (be careful).
Use === when checking strpos(...) {{c2::!==falsy}}.
__DIR__ gives the current file’s {{c1::directory path}} (safer than relative paths).
require vs require_once: require_once adds overhead; prefer {{c1::autoloading}} for classes instead of many *_once.
password_hash PASSWORD_DEFAULT so the algorithm can {{c1::in_arrayinterpolate variables directly into SQL; bind them as {{c1::true}parameters}}match has no fall-through and will throw UnhandledMatchError if no case matches and there’s no {{c1::=== __construct(private Logger $logger) is promoted property syntax (PHP {{If you tell me yourwhether courseyou’re focususing (e.g.PHP 7.4, 8.0–8.4, and whether you’re focusing on WordPress pluginplugin/theme dev, or Laravel,general raw PHP, PDO/MySQL, CLI scripting) and your PHP versionbackend, I can generate a second deck with more targetedscenario-based clozes (e.g., namespaces/PSR-12, PHPUnit, HTTPdebugging, forms, fileauth, uploads,PDO orpitfalls) WP hooks).🧠✅