最終更新:
bokkuri_orz 2014年09月16日(火) 02:21:41履歴
●ソースコード
class Singleton
{
private static $instance = null;
// コンストラクタ。privateなので、new が禁止される。
private function __construct()
{
echo 'singleton> '.get_class($this).'.__construct()<br>';
}
static public function getInstance()
{
if($instance == null) $instance = new Singleton;
return $instance;
}
}
Singleton::getInstance(); // シングルトンアクセス
$obj = new Singleton(); // エラー
●出力結果
singleton> Singleton.__construct() Fatal error: Call to private Singleton::__construct() from invalid context in /web/com/139023473323246/main.php on line 26
try
{
$host_name = 'localhost';
$db_name = 'test_db';
$dsn = "mysql:host=$host_name;dbname=$db_name;charset=sjis";
$user = 'root';
$password = 'root';
// PDOインスタンス生成(データベース接続)
$dbh = new PDO($dsn, $user, $password);
}
catch(PDOException $e)
{
print("database connection error.<br>");
}
$dbh; // PDOインスタンス
try
{
// SQLステートメント。 :user_id はプレースメントホルダ。bindValue()で値がセットされる。
$sql = 'select * from test_table where user_id = :user_id';
// SQLステートメントの準備。後で、execute()で実行する。
$stmt = $dbh->prepare($sql);
// ステートメント内のプレースメントホルダに値を設定
$stmt->bindValue(':user_id', $id, PDO::PARAM_STR);
// SQLステートメントを実行
$flag = $stmt->execute();
if($flag)
{
// 結果セットから全ての行を配列で取得
$records = $stmt->fetchAll();
// レコード数
$num = count($records);
if($num > 0)
{
// 1件目のレコードを出力
var_dump($records[0]);
// 1件目のレコードのカラム'name'の値を出力
var_dump($records[0]['name']);
}
}
}
catch(PDOException $e)
{
print('Error : '.$e->getMessage());
}
タグ


最新コメント