20241024
20241024
code:php
<?php
function createConnection(): \PDO {
$pdo = new \PDO("sqlite:memory");
return $pdo;
}
function createDatabase(\PDO $pdo) {
$sql = "-- person テーブル(人の基本情報)
CREATE TABLE person (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sex_type TEXT NOT NULL,
person_name TEXT NOT NULL
);
-- marries テーブル(結婚情報)
CREATE TABLE marries (
spause_1 INTEGER NOT NULL,
spause_2 INTEGER NOT NULL,
married_datetime TEXT NOT NULL,
PRIMARY KEY (spause_1, spause_2),
FOREIGN KEY (spause_1) REFERENCES person(id),
FOREIGN KEY (spause_2) REFERENCES person(id)
);";
$pdo->exec($sql);
}
function db_marries_insert(\PDO $pdo, array $param): void {
$stmt = $pdo->prepare("INSERT INTO marries VALUES(?, ?, ?)");
$stmt->execute($param);
}
function db_person_insert(\PDO $pdo, array $param): void {
$stmt = $pdo->prepare("INSERT INTO person(sex_type, person_name) VALUES(?, ?)");
$stmt->execute($param);
}
$pdo = createConnection();
createDatabase($pdo);
$stmt = $pdo->prepare("SELECT sex_type AS sex, person_name AS name FROM person ORDER BY id DESC;");
$stmt->execute();
enum Sex: string {
case Female = "f";
case Male = "m";
}
class Person {
public Sex $sex;
public string $name;
function __construct(...$row) {
}
function greet() {
$sex = match ($this->sex) {
Sex::Female => "female",
Sex::Male => "male",
};
echo "hi! i'm $this->name, $sex\n";
}
}
function convert ($sex, $name) {
$convertedSex = match ($sex) {
'f' => Sex::Female,
'm' => Sex::Male,
};
return new Person($convertedSex, $name);
}
$people = $stmt->fetchAll(PDO::FETCH_FUNC, 'convert');
// foreach($people as $r){ $r->greet(); }
print_r($people);