10分でPHPを学ぶ
PHPは、ウェブ開発向けに設計された広く使用されているサーバーサイドスクリプト言語です。元々「Personal Home Pages」のために作られたPHPは、現在「PHP: Hypertext Preprocessor」を意味します。このチュートリアルでは、PHP 8.3+の機能を網羅し、モダンなPHP開発を素早く学習できます。
1. 最初のPHPプログラムを書く
簡単なプログラムから始めましょう。hello.php
というファイルを作成し、以下のコードを入力してください:
<?php
echo "Hello, World!";
?>
ファイルを保存し、Webサーバーまたは PHP CLI を使用して実行します:
php hello.php
出力は以下のようになります:
Hello, World!
この簡単なプログラムは、PHPの基本的な出力機能を示しています。echo
文はテキストを表示するために使用されます。PHPコードは<?php
と?>
タグで囲まれています。
2. 基本的な構文
PHPの構文は簡単で、CやPerlに似ています。PHPコードはサーバー上で実行され、結果はプレーンHTMLとしてブラウザに送信されます。
<?php
// This is a single-line comment
echo "Hello, World!";
/*
This is a multi-line comment
spanning multiple lines
*/
?>
PHPの基本的な構文規則:
- PHPタグ:PHPコードは
<?php ... ?>
タグで囲む必要があります - コメント:単行コメントは
//
または#
を使用し、複数行コメントは/* ... */
を使用します - 文:セミコロン
;
で終わります - 大文字小文字の区別:変数名は大文字小文字を区別しますが、関数名は区別しません
- 変数:
$
記号で始まります
<?php
$name = "John"; // Variable (case-sensitive)
$Name = "Jane"; // Different variable
echo $name; // Outputs: John
ECHO $Name; // Outputs: Jane (ECHO works same as echo)
?>
3. 変数とデータ型
PHPでは、変数はデータを格納するコンテナです。PHPは緩い型付けの言語で、変数の型を明示的に宣言する必要がありません。
変数の命名規則:
$
記号で始める必要があります- 文字、数字、アンダースコアを含むことができます
- 数字で始めることはできません
- 大文字小文字を区別します
PHPの主なデータ型:
- String:引用符で囲まれたテキストデータ
- Integer:整数
- Float:小数
- Boolean:
true
またはfalse
- Array:値のコレクション
- Object:クラスのインスタンス
- NULL:値がないことを表します
- Resource:外部リソースへの参照
<?php
$name = "Alice"; // String
$age = 25; // Integer
$height = 5.8; // Float
$is_student = true; // Boolean
$grades = [90, 85, 92]; // Array
$data = null; // NULL
// Type checking
var_dump($name); // string(5) "Alice"
echo gettype($age); // integer
?>
3.1 文字列操作
文字列は単一引用符または二重引用符を使用して定義でき、異なる動作をします:
<?php
$single = 'Single quote string';
$double = "Double quote string";
$name = "John";
$greeting = "Hello, $name!"; // Variable interpolation
$greeting2 = 'Hello, $name!'; // No interpolation
echo $greeting; // Hello, John!
echo $greeting2; // Hello, $name!
// String concatenation
$full_name = "John" . " " . "Doe";
$full_name .= " Jr."; // Append
// String functions
echo strlen($name); // String length: 4
echo strtoupper($name); // JOHN
echo strtolower($name); // john
echo substr($name, 0, 2); // Jo
?>
3.2 配列
PHPは添字配列、連想配列、多次元配列をサポートしています:
<?php
// Indexed array
$fruits = ["apple", "banana", "orange"];
$numbers = array(1, 2, 3, 4, 5);
// Associative array
$person = [
"name" => "John",
"age" => 30,
"city" => "New York"
];
// Multidimensional array
$students = [
["name" => "Alice", "grade" => 90],
["name" => "Bob", "grade" => 85],
["name" => "Carol", "grade" => 92]
];
// Accessing arrays
echo $fruits[0]; // apple
echo $person["name"]; // John
echo $students[0]["grade"]; // 90
// Array functions
echo count($fruits); // 3
array_push($fruits, "grape"); // Add element
print_r($fruits); // Display array
?>
4. 演算子
PHPは様々な操作のための各種演算子を提供しています:
4.1 算術演算子
<?php
$a = 10;
$b = 3;
echo $a + $b; // Addition: 13
echo $a - $b; // Subtraction: 7
echo $a * $b; // Multiplication: 30
echo $a / $b; // Division: 3.333...
echo $a % $b; // Modulus: 1
echo $a ** $b; // Exponentiation: 1000
?>
4.2 比較演算子
<?php
$x = 5;
$y = "5";
var_dump($x == $y); // true (equal value)
var_dump($x === $y); // false (identical type and value)
var_dump($x != $y); // false
var_dump($x !== $y); // true
var_dump($x > 3); // true
var_dump($x <= 5); // true
?>
4.3 論理演算子
<?php
$a = true;
$b = false;
var_dump($a && $b); // false (AND)
var_dump($a || $b); // true (OR)
var_dump(!$a); // false (NOT)
var_dump($a and $b); // false (AND, lower precedence)
var_dump($a or $b); // true (OR, lower precedence)
?>
5. 制御フロー
5.1 if文
<?php
$age = 20;
if ($age >= 18) {
echo "Adult";
} elseif ($age >= 13) {
echo "Teen";
} else {
echo "Child";
}
// Ternary operator
$status = ($age >= 18) ? "Adult" : "Minor";
echo $status;
// Null coalescing operator (PHP 7+)
$username = $_GET['user'] ?? 'guest';
?>
5.2 switch文
<?php
$day = "Monday";
switch ($day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
echo "Weekday";
break;
case "Saturday":
case "Sunday":
echo "Weekend";
break;
default:
echo "Invalid day";
}
?>
5.3 ループ
forループ:
<?php
for ($i = 0; $i < 5; $i++) {
echo "Number: $i\n";
}
// foreach for arrays
$fruits = ["apple", "banana", "orange"];
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
// foreach with key-value pairs
$person = ["name" => "John", "age" => 30];
foreach ($person as $key => $value) {
echo "$key: $value\n";
}
?>
whileとdo-whileループ:
<?php
$count = 0;
while ($count < 3) {
echo "Count: $count\n";
$count++;
}
$num = 0;
do {
echo "Number: $num\n";
$num++;
} while ($num < 3);
?>
6. 関数
PHPの関数は、特定のタスクを実行する再利用可能なコードブロックです:
<?php
// Basic function
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice");
// Function with default parameters
function calculate_area($length, $width = 1) {
return $length * $width;
}
echo calculate_area(5); // 5 (width defaults to 1)
echo calculate_area(5, 3); // 15
// Variable arguments
function sum(...$numbers) {
return array_sum($numbers);
}
echo sum(1, 2, 3, 4); // 10
// Anonymous functions (closures)
$multiply = function($a, $b) {
return $a * $b;
};
echo $multiply(4, 5); // 20
?>
6.1 変数のスコープ
<?php
$global_var = "I'm global";
function test_scope() {
global $global_var;
$local_var = "I'm local";
echo $global_var; // Accessible with 'global' keyword
echo $local_var; // Local to this function
}
test_scope();
// Static variables
function counter() {
static $count = 0;
$count++;
echo "Count: $count\n";
}
counter(); // Count: 1
counter(); // Count: 2
counter(); // Count: 3
?>
7. オブジェクト指向プログラミング
PHPはクラスとオブジェクトを使用したオブジェクト指向プログラミングをサポートしています:
<?php
class Person {
// Properties
private $name;
private $age;
public $city;
// Constructor
public function __construct($name, $age, $city = "Unknown") {
$this->name = $name;
$this->age = $age;
$this->city = $city;
}
// Methods
public function getName() {
return $this->name;
}
public function setAge($age) {
if ($age > 0) {
$this->age = $age;
}
}
public function getAge() {
return $this->age;
}
public function introduce() {
return "Hi, I'm {$this->name}, {$this->age} years old from {$this->city}";
}
}
// Creating objects
$person1 = new Person("John", 25, "New York");
$person2 = new Person("Jane", 30);
echo $person1->introduce();
echo $person2->getName();
?>
7.1 継承
<?php
class Animal {
protected $name;
protected $species;
public function __construct($name, $species) {
$this->name = $name;
$this->species = $species;
}
public function makeSound() {
return "{$this->name} makes a sound";
}
public function getInfo() {
return "{$this->name} is a {$this->species}";
}
}
class Dog extends Animal {
private $breed;
public function __construct($name, $breed) {
parent::__construct($name, "Dog");
$this->breed = $breed;
}
public function makeSound() {
return "{$this->name} barks";
}
public function fetch() {
return "{$this->name} fetches the ball";
}
}
$dog = new Dog("Buddy", "Golden Retriever");
echo $dog->getInfo(); // Buddy is a Dog
echo $dog->makeSound(); // Buddy barks
echo $dog->fetch(); // Buddy fetches the ball
?>
8. エラーハンドリング
PHPは、エラーと例外を処理するためのいくつかの方法を提供しています:
<?php
// Try-catch for exceptions
try {
$result = 10 / 0;
throw new Exception("Custom error message");
} catch (DivisionByZeroError $e) {
echo "Division by zero error: " . $e->getMessage();
} catch (Exception $e) {
echo "General error: " . $e->getMessage();
} finally {
echo "This always executes";
}
// Custom exception class
class CustomException extends Exception {
public function errorMessage() {
return "Custom error on line {$this->getLine()} in {$this->getFile()}: {$this->getMessage()}";
}
}
try {
throw new CustomException("Something went wrong!");
} catch (CustomException $e) {
echo $e->errorMessage();
}
?>
9. ファイル操作
PHPは、ファイル操作のための様々な関数を提供しています:
<?php
// Reading files
$content = file_get_contents("example.txt");
echo $content;
// Writing files
file_put_contents("output.txt", "Hello, PHP!");
// File operations with error handling
if (file_exists("data.txt")) {
$lines = file("data.txt", FILE_IGNORE_NEW_LINES);
foreach ($lines as $line) {
echo $line . "\n";
}
} else {
echo "File not found";
}
// Working with file handles
$handle = fopen("log.txt", "a");
if ($handle) {
fwrite($handle, "Log entry: " . date("Y-m-d H:i:s") . "\n");
fclose($handle);
}
?>
10. フォームとHTTPの処理
PHPはWebフォームとHTTPリクエストの処理に優れています:
<?php
// HTML form (save as form.html)
/*
<form method="POST" action="process.php">
<input type="text" name="username" placeholder="Username">
<input type="email" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button type="submit">Submit</button>
</form>
*/
// Processing form data (process.php)
if ($_POST) {
$username = $_POST['username'] ?? '';
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
// Validation
if (empty($username) || empty($email) || empty($password)) {
echo "All fields are required";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
} else {
// Process the data
echo "Welcome, " . htmlspecialchars($username);
// Hash password
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// Save to database, etc.
}
}
// Working with GET parameters
$page = $_GET['page'] ?? 1;
$category = $_GET['category'] ?? 'all';
echo "Page: $page, Category: $category";
?>
11. データベース操作
PHPは、特にMySQLとのデータベース操作でよく使用されます:
<?php
// Database connection using PDO
try {
$pdo = new PDO(
"mysql:host=localhost;dbname=mydb;charset=utf8",
"username",
"password",
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
// Prepared statements (secure)
$stmt = $pdo->prepare("SELECT * FROM users WHERE age > ? AND city = ?");
$stmt->execute([18, "New York"]);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "User: " . $row['name'] . "\n";
}
// Insert data
$stmt = $pdo->prepare("INSERT INTO users (name, email, age) VALUES (?, ?, ?)");
$stmt->execute(["John Doe", "[email protected]", 25]);
echo "Last inserted ID: " . $pdo->lastInsertId();
} catch (PDOException $e) {
echo "Database error: " . $e->getMessage();
}
?>
12. モダンなPHP機能(PHP 8.0+)
PHP 8.0+では多くの近代的な機能が導入されました:
<?php
// Named arguments (PHP 8.0+)
function createUser($name, $email, $age = 18, $active = true) {
return compact('name', 'email', 'age', 'active');
}
$user = createUser(
name: "John",
email: "[email protected]",
active: false
);
// Match expression (PHP 8.0+)
$status_code = 200;
$message = match($status_code) {
200, 201 => 'Success',
400 => 'Bad Request',
404 => 'Not Found',
500 => 'Server Error',
default => 'Unknown Status'
};
// Nullsafe operator (PHP 8.0+)
$user_name = $user?->profile?->name ?? 'Unknown';
// Constructor property promotion (PHP 8.0+)
class User {
public function __construct(
public string $name,
public string $email,
public int $age = 18,
private bool $active = true
) {}
public function isActive(): bool {
return $this->active;
}
}
$user = new User("John", "[email protected]", 25);
echo $user->name; // John
// Enums (PHP 8.1+)
enum Status {
case PENDING;
case APPROVED;
case REJECTED;
public function label(): string {
return match($this) {
Status::PENDING => 'Pending',
Status::APPROVED => 'Approved',
Status::REJECTED => 'Rejected',
};
}
}
$status = Status::PENDING;
echo $status->label(); // Pending
?>
13. ベストプラクティスとコツ
重要なPHPのベストプラクティスをいくつか紹介します:
<?php
// 1. Always use PHP opening tags
// Good: <?php
// Avoid: <? (short tags)
// 2. Use prepared statements for database queries
// Prevents SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
// 3. Validate and sanitize input
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$name = htmlspecialchars($_POST['name'], ENT_QUOTES, 'UTF-8');
// 4. Use meaningful variable names
// Good:
$user_age = 25;
$is_active = true;
// Bad:
$a = 25;
$flag = true;
// 5. Handle errors gracefully
function divide($a, $b) {
if ($b == 0) {
throw new InvalidArgumentException("Division by zero");
}
return $a / $b;
}
// 6. Use type declarations (PHP 7+)
function calculateTotal(array $items): float {
return array_sum($items);
}
// 7. Organize code with namespaces
namespace App\Models;
class User {
// class implementation
}
// 8. Use composer for dependency management
// composer.json example:
/*
{
"require": {
"monolog/monolog": "^2.0"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
*/
?>
PHPは、ウェブ開発に最適な強力で柔軟な言語です。このチュートリアルでは、PHPアプリケーションの構築を始めるために必要な基本概念を網羅しました。これらの概念を実践し、LaravelやSymfonyなどのPHPフレームワークを探索し、学習を続けてください!