Anatomy of a PHP file
PHP is a widely-used open-source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.
File extensions: .php
Every part of the example below is labelled and explained. This page is one of 55 annotated tours on AnatomyOf, a free, open-source project by LunarWerx Studios.
What is inside a PHP file
Opening tag
<?php switches the parser from HTML text into PHP code mode.
Everything outside <?php ... ?> is sent to the output verbatim as plain text, which is what lets a .php file mix HTML markup and PHP logic in the same document. A template can drop in and out of PHP mode as many times as it needs. <?php (with the trailing space or newline) is the canonical form; the short echo tag <?= is also common for printing a single expression inline in a template. A shorthand <? tag exists but is disabled by default (short_open_tag) on most installations, so <?php is the only form that is guaranteed to work everywhere. Because the tag itself is what triggers execution, a
Comment
Single-line (//, #) or block (/* ... */), ignored by the interpreter.
// and # both start a comment that runs to the end of the line; // is the more idiomatic choice in most style guides, while # is more often seen in shell-style config or inline directives. A /* ... */ block comments out everything between the delimiters, including multiple lines, but cannot be nested. Documentation comments written as /** ... */ (two asterisks) follow the same PHPDoc convention as Javadoc: tags like @param and @return describe a function's signature for humans and for IDE tooling, even though PHP itself never checks them at runtime.
Namespace declaration
Organizes code into logical groups and avoids name collisions.
A namespace MyProject\Models; statement, when present, must be the first statement in the file (aside from comments and the opening tag). It groups related classes, functions, and constants under a prefix, so two libraries can each define a class named User without colliding, as long as they live in different namespaces. Namespaces are separated with a backslash, mirroring the directory-like structure most autoloaders (including Composer's PSR-4 standard) expect: MyProject\Models\User typically resolves to a file at src/Models/User.php. Code outside the namespace refers back to it with a fully
Use statement
use imports a class, function, or namespace so it can be referenced by a short name.
use DateTime; (or use App\Services\Mailer;) lets the rest of the file refer to DateTime instead of its fully qualified name. Without the import, code outside the global namespace would have to write \DateTime, a leading backslash forcing PHP to look in the root namespace instead of the current one. use ... as Alias renames an imported symbol when two libraries export something with the same short name, and a single file can carry as many use statements as it needs, conventionally grouped just below the namespace line.
Class definition
The blueprint for objects, defined with class ... { }.
A class block defines a new type made up of properties (data) and methods (behavior). PHP is thoroughly object-oriented from PHP 5 onward, though unlike Java it does not require one class per file or a filename match. A single file can define several classes, functions, and top-level statements together. Classes support single inheritance (class Admin extends User) and can implement any number of interfaces (implements Countable, ArrayAccess). Traits (use SomeTrait; inside the class body) offer a form of horizontal code reuse for when inheritance alone will not fit.
Property (class variable)
Data stored within an object, declared with a visibility modifier.
A property declared in the class body, like private DateTime $createdAt;, holds state that belongs to each object created from the class. public, protected, and private control whether outside code, subclasses, or only the class itself can read and write the property directly. As of PHP 7.4+, properties can carry an optional type declaration (string $name), which the engine enforces at assignment time, a mismatched type throws a TypeError rather than silently coercing. Marking a property readonly (PHP 8.1+) additionally forbids changing it after it is first set.
Constructor method
__construct runs automatically when a new object is created with new.
__construct is a "magic method". Its double-underscore name is reserved by the engine and called for you rather than invoked directly. new User("Alice") allocates the object, then immediately calls __construct("Alice") on it, which is the conventional place to assign incoming arguments to properties, typically via $this. PHP 8 also supports constructor property promotion, letting public function __construct(private string $name) {} declare and assign a property in one line without a separate property declaration or an explicit $this->name = $name; body statement.
Method / function definition
A reusable block of code defined with function, inside or outside a class.
function greet(): string { ... } defines a function; the same syntax inside a class body defines a method, callable on an instance as $alice->greet(). An optional return type after the colon (here string) is enforced by the engine when strict typing is enabled with declare(strict_types=1); at the top of the file. Methods and functions can take typed parameters, default values, and a variadic ...$args catch-all. Inside an instance method, $this refers to the object the method was called on and is how the body reaches the object's own properties, e.g. $this->name.
Variable
Starts with $, dynamically typed, no declaration keyword needed.
Every PHP variable name is prefixed with a sigil, $, which is what lets the engine tell a bare word like a function name apart from a variable reference at a glance. Variables need no declaration; assigning to $alice the first time creates it, and its type is whatever value it currently holds rather than something fixed up front. Variables are function-scoped by default: a variable created inside a function is invisible outside it, and a global variable is likewise invisible inside a function unless explicitly imported with global $name; or captured by a closure's use (...) clause.
Object instantiation
Creates a new instance of a class with new.
new User("Alice") allocates a new object, runs its constructor with the given arguments, and evaluates to a reference to that object. Every object lives on the heap and is accessed through a reference: assigning $bob = $alice copies the reference, so both variables point at the same underlying object, while clone $alice produces an independent copy. Built-in classes are instantiated the same way as user-defined ones, as in new DateTime() for the current date and time. PHP's garbage collector reclaims an object automatically once nothing references it any longer; there is no manual free.
String interpolation
Embeds variables directly inside double-quoted strings.
A double-quoted string like "Hello, my name is $name." substitutes $name's value directly into the text at runtime; single-quoted strings never interpolate and treat $name as literal characters. Reaching into an object property or array element needs the curly-brace form, "{$this->name}" or "{$items['key']}", so the parser knows exactly where the expression ends. Interpolation is generally preferred over concatenation with . for readability when mixing several variables into one string, though both compile to the same underlying operation and neither is meaningfully faster than the other in mo
Official PHP site · All languages on AnatomyOf
The interactive tour needs JavaScript. Enable it to hover a callout and trace it into the code.