PHP Syntax
PHP code lives between <?php ... ?> tags. Everything outside those tags is sent to the browser unchanged.
The tags
PHP
<!DOCTYPE html>
<html>
<body>
<h1><?php echo 'Hello, world'; ?></h1>
<p>The time is <?= date('H:i') ?>.</p>
</body>
</html>
<?= $x ?> is shorthand for <?php echo $x; ?>.
Pure PHP files
If a file contains only PHP code, omit the closing ?>. It avoids accidental trailing whitespace that could break headers / output:
PHP — UserService.php
<?php
namespace App;
class UserService
{
public function ...
}
Statements end with ;
PHP
$name = 'Ada'; echo "Hello, $name"; $age = 36;
Case sensitivity
| Thing | Case-sensitive? |
|---|---|
Variables ($name) | Yes |
| Functions, methods, classes, keywords | No — but use the documented case |
| Constants (by default) | Yes |
Whitespace is mostly free
PHP doesn't care if you put a statement on one line or three — but the community uses PSR-12. Run php-cs-fixer or pint to format automatically.
Tip: A common bug — forgetting
; at the end of a line — usually shows up as a syntax error pointing at the next line. Look one above.Example
Exercise
Wrap PHP code with the standard opening tag.
echo 'hi'; ?>
Five characters; starts with <.
Discussion
Loading…