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.

PHP
<?php
// PHP code goes here
echo "Hello World";
?>

(2) Short Echo Tag

PHP
<?= "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:

PHP
<h1>Welcome, <?= $username ?></h1>
⚠️ Warning: Historically, there was also a <? ?> 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
<?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

PHP
<!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>
▶ 試してみよう
💡 Tip: PHP offers two styles for mixing with HTML. Use <?= ?> 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
<?php
echo "First line";
echo "Second line";
$name = "PHP";
?>

Rules:

🔥 Common Mistake: Forgetting a semicolon is the most frequent beginner error in PHP. The error message is usually 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_CONSTmy_const
Function names ❌ No echo() = ECHO() = Echo()
Class / method names ❌ No MyClass = myclass
Keywords ❌ No if = IF = If

▶ サンプル: Variables Are Case-Sensitive

PHP
<?php
$color = "red";
$Color = "blue";
$COLOR = "green";

echo $color;  // Output: red
echo $Color;  // Output: blue
echo $COLOR;  // Output: green
?>
▶ 試してみよう
💡 Tip: Even though function names and keywords are case-insensitive, always use lowercase. Code consistency matters more than flexibility.


5. Comments

PHP supports three comment styles:

PHP
<?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
💡 Tip: Don't write obvious comments. // 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 print
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
<?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
?>
▶ 試してみよう
💡 Tip: Always use 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
<?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";
?>
▶ 試してみよう
⚠️ Warning: \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.

❓ よくある質問

Q Why does my .php file show raw source code in the browser instead of executing?
A You probably double-clicked the .php file (which opens it via the file:/// protocol), or the server doesn't have PHP installed/enabled. PHP files must be accessed via http://localhost/.
Q What's the difference between <?php and <?=?
A <?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.
Q Can echo output numbers and strings together?
A Yes. PHP auto-converts types. echo 42 . " is the answer"; outputs "42 is the answer" — the integer 42 is automatically converted to a string.

📖 まとめ

📝 練習問題

  1. Create a PHP page that includes your name (using a variable), the current date (using the date function), and an HTML table — all output through echo.
  2. Try all three comment styles — //, #, and /* */ — in the same file and confirm they all work.
  3. Write a comparison example that uses both \n and <br> to understand how they differ in the browser.
Web-Tutorial.com

Web-Tutorial 技術チーム

複数の開発者によって共同維持されているプログラミングチュートリアルプラットフォーム。各チュートリアルは専門分野の開発者が執筆・レビューしています。正確で信頼性の高いコンテンツを目指しています — 問題を見つけた場合はお知らせください。

100%