追記
php
1class Test 2{ 3 4 public $hoge = "cccc"; 5 6 7 static public function getNew() 8 { 9 echo "aaaaa/"; 10 echo $this->hoge; 11 } 12} 13 14class Child extends Test 15{ 16} 17 18Child::getNew();
謎
上記のコードを実行すると、aaaaa/とだけ表示されます。何故、ccccは表示されないのでしょうか
やりたいこと
phpでオブジェクト指向を実践しています。PDOのdb接続と、selectをクラスで分割し、オブジェクト思考なコードを書く際、疑問が湧いたので質問します。書くの全体のコードは極めて正しく動くのですが。。
#疑問点
下記全体のコードの一部分、コンストラクトがありますが、$this->dbh
というのはクラスDatabaseで作成した変数ですよね?newでDatabaseクラスのインスタンスを作って仕舞えば、インスタンス変数の$dbを利用せずとも、$thisが使え$this->dbh
という風にclass Databaseの実装を利用することが可能なのでしょうか。
function __construct() { $db=new Database; $this->dbh=$db->getDBH(); }
実装
<?PHP class Database { function getDBH() { try{ $dsn = 'mysql:host=localhost; dbname=test1;charset=utf8;'; $user = 'root'; $password = 'root'; $dbh = new PDO($dsn, $user,$password); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,false); return $dbh; }catch(PDOException $e){ die($e->getMessage()); } } } class DataSelect { function __construct() { $db=new Database; $this->dbh=$db->getDBH(); } function test() { try{ $sql="SELECT * FROM tb"; $stmt = $this->dbh->prepare($sql); $stmt->execute([]); $rows=$stmt->fetchAll(PDO::FETCH_ASSOC); print_r($rows); }catch(PDOException $e){ die($e->getMessage()); } } } $myExec=new DataSelect; $myExec->test();
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/04/04 23:41
2018/04/04 23:44
2018/04/04 23:47
退会済みユーザー
2018/04/04 23:47
2018/04/04 23:47
2018/04/04 23:51
2018/04/04 23:53
2018/04/04 23:55
2018/04/04 23:56
2018/04/04 23:57
2018/04/04 23:58
2018/04/05 00:00
2018/04/05 00:03
退会済みユーザー
2018/04/05 00:08
2018/04/05 00:08
2018/04/05 00:15 編集
2018/04/05 00:14 編集
2018/04/05 00:19
2018/04/05 00:33
2018/04/05 01:03
2018/04/05 01:04
2018/04/05 01:12
2018/04/05 01:16 編集
2018/04/05 01:15
2018/04/05 01:18