Understand PHP Code Before You Run It
PHP files can be checked for syntax errors before you run them. Learn to follow what the code does, not just what it looks like.
43 articles
Latest articles
-
Should a Custom PHP Exception Extend Exception or an SPL Subclass?
Choose LogicException for a program-logic failure, RuntimeException for an operational failure, or Exception when that distinction adds little.
-
Throw a PHP Exception When an Operation Fails, Then Catch It at the Caller
Use distinct exceptions for invalid input and an operation that cannot finish, let an intermediate function pass them through, and catch them where a useful response is possible.
-
Specify Required and Optional Array Keys with PHPDoc Shapes
Use `array{id: int, name: string, nickname?: string}` to give PHPStan or Psalm known keys and value types to analyze.
-
Declare a PHP Trait Property Without Conflicting With the Using Class
A trait property becomes part of the using class. In PHP 8.x, a same-named class property needs a compatibility check, not an automatic rejection.
-
Pass a PHP Closure to array_map to Look Up Values by Key
Give array_map a callback that receives each key and reads its value from a lookup array, using an arrow function or a traditional anonymous function.
-
Understand PHP execution and behavior
Produce PHP Values Only When foreach Requests Them
Trace a counted generator through a full pass and an early break, then compare its markers with an array built before iteration.
-
Annotate an Array of Task Objects with PHPDoc
Use `Task[]` or `array<Task>` to describe the values PHPStan should expect, and reserve `list<Task>` for arrays whose keys must also start at zero and stay sequential.
-
Understand PHP execution and behavior
List Declared PHP Classes in a Namespace with get_declared_classes()
Read the class names available to the current script, inspect how your runtime returns the example names, then filter them using a namespace prefix with a trailing separator.
-
Restrict Object Classes When Calling PHP unserialize()
Pass an allowed_classes list or false, then check whether the restored value is the expected object or __PHP_Incomplete_Class before using it.
-
Configure PHP and connected services
Connect PHP to MySQL with PDO and Run a Prepared SELECT
Use a MySQL DSN and credentials to connect with PDO, then prepare a fixed query, execute it, and inspect the fetched rows.
