PHP: PHPの基本構文
PHP's syntax borrows from C, Java, and Perl. If you've learned any programming language before, PHP will feel familiar. If you haven't — no worries. This lesson is your starting point.
1. PHP Tags
PHP code must be enclosed in PHP tags so the server can recognize and execute it.
(1) Standard Tag (Recommended)
<?php
// PHP code goes here
echo "Hello World";
?>
(2) Short Echo Tag
<?= "Hello World" ?> <!-- Equivalent to <?php echo "Hello World"; ?> -->
<?= ?> is shorthand for <?php echo ... ?> and has been always available since PHP 5.4. It's especially handy for embedding variables in HTML:
<h1>Welcome, <?= $username ?></h1>
<? ?> short tag (without php), but that syntax depends on the short_open_tag setting in php.ini and may not work across different servers. Always use the <?php standard tag.
(3) The Closing ?> Can Be Omitted
If a file contains only PHP code (no HTML), it's recommended to omit the closing ?>:
<?php
// Pure PHP file — omit the closing ?>
echo "Done";
// End of file — no ?>
Why? To prevent accidental whitespace after ?> from interfering with HTTP headers.
2. Mixing PHP and HTML
One of PHP's most unique features: you can freely mix HTML and PHP in the same file:
▶ サンプル: PHP Embedded in HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Site</title>
</head>
<body>
<h1><?= "Welcome!" ?></h1>
<p>Current time: <?= date("H:i:s") ?></p>
<?php
$isLogin = true;
if ($isLogin):
?>
<p>✅ You are logged in</p>
<?php else: ?>
<p>❌ Please log in</p>
<?php endif; ?>
</body>
</html>
<?= ?> for quick output; wrap larger logic blocks in <?php ... ?>. The alternative syntax for control structures (if (): ... endif;) is more readable than curly braces {}.
3. Statements and Semicolons
Every statement in PHP must end with a semicolon ;:
<?php
echo "First line";
echo "Second line";
$name = "PHP";
?>
Rules:
- End each executable statement with
; - The last statement in a PHP block can technically omit the semicolon (not recommended — it hurts consistency)
?>itself implies a semicolon, soecho "Hi" ?>is technically valid (but still add the;for consistency)
Parse error: syntax error, unexpected ... — when you see that, check your semicolons first.
4. Case Sensitivity Rules
PHP has different case-sensitivity rules for different things, which can be confusing:
| Type | Case-Sensitive? | Example |
|---|---|---|
| Variable names | ✅ Yes | $name ≠ $Name ≠ $NAME |
| Constant names | ✅ Yes | MY_CONST ≠ my_const |
| Function names | ❌ No | echo() = ECHO() = Echo() |
| Class / method names | ❌ No | MyClass = myclass |
| Keywords | ❌ No | if = IF = If |
▶ サンプル: Variables Are Case-Sensitive
<?php
$color = "red";
$Color = "blue";
$COLOR = "green";
echo $color; // Output: red
echo $Color; // Output: blue
echo $COLOR; // Output: green
?>
5. Comments
PHP supports three comment styles:
<?php
// This is a single-line comment (C++ style)
# This is also a single-line comment (Shell style)
/*
* This is a multi-line comment
* It can span multiple lines
* Just like in C
*/
/**
* This is a documentation comment
* Used to document functions and classes
* @param string $name The username
* @return string A greeting message
*/
function greet($name) {
return "Hello, " . $name;
}
?>
| Style | Syntax | Notes |
|---|---|---|
| Double slash | // comment |
Most common — recommended |
| Hash | # comment |
Shell style — rarely used |
| Slash-star | /* */ |
Multi-line comments |
| Doc comment | /** */ |
For function/class API documentation |
// Assign 1 to $a is unnecessary — the code already says that. Comments should explain why something is done, not what is done.
6. echo vs. print
Both echo and print are PHP output statements. They're very similar, with subtle differences:
| echo | ||
|---|---|---|
| Multiple arguments | ✅ echo "a","b","c"; |
❌ Only one |
| Return value | ❌ None | ✅ Always returns 1 |
| Speed | Slightly faster | Slightly slower |
| Usage share | 95% echo | Rarely used |
▶ サンプル: Using echo
<?php
// Output a string
echo "Hello World";
// Output multiple (comma-separated)
echo "My", " name", " is", " John"; // Output: My name is John
// Output HTML tags
echo "<h2>This is a heading</h2>";
// Output a variable
$name = "Alice";
echo "Hello, " . $name; // Hello, Alice
// Double quotes parse variables directly
echo "Hello, $name"; // Hello, Alice
?>
echo. Unless you're in a context that requires a return value (extremely rare), you don't need print.
7. Escape Characters
Use the backslash \ to represent special characters in strings:
| Escape Sequence | Meaning |
|---|---|
\n |
Newline |
\r |
Carriage return |
\t |
Tab |
\\ |
Backslash itself |
\$ |
Dollar sign (prevents it from being treated as a variable) |
\" |
Double quote |
▶ サンプル: Escape Characters
<?php
echo "Line one\nLine two\nLine three";
// For visible line breaks in the browser, use <br>
echo "Line one<br>Line two<br>Line three";
echo "He said: \"PHP is easy!\"";
echo "The path is C:\\xampp\\htdocs";
echo "The price is \$100";
?>
\n doesn't produce a visible line break in HTML (browsers ignore plain-text newlines). To break a line on a web page, use the <br> tag with CSS styling. \n only affects how the HTML source code looks.
❓ よくある質問
file:/// protocol), or the server doesn't have PHP installed/enabled. PHP files must be accessed via http://localhost/.<?php and <?=?<?php is the full PHP tag — write any PHP code inside it. <?= ?> is shorthand for <?php echo ... ?> and is only used to output a single expression.echo 42 . " is the answer"; outputs "42 is the answer" — the integer 42 is automatically converted to a string.📖 まとめ
- PHP code goes inside
<?php ?>tags;<?= ?>is shorthand for echo - For pure PHP files, omit the closing
?> - PHP and HTML can be freely mixed in the same file
- Each statement ends with a semicolon
; - Variable names are case-sensitive; function names and keywords are not (but always use lowercase)
- Three comment styles:
//#/* */— stick with// echois the most common output statement;printis almost never needed- Escape characters use backslash
\; for HTML line breaks, use<br>
📝 練習問題
- Create a PHP page that includes your name (using a variable), the current date (using the
datefunction), and an HTML table — all output throughecho. - Try all three comment styles —
//,#, and/* */— in the same file and confirm they all work. - Write a comparison example that uses both
\nand<br>to understand how they differ in the browser.