我对OO编程有点陌生,很难理解为什么一种机制有效而另一种机制无效。
我已经创建了一个简单的类,该类将返回MySQL数据库句柄。我尝试直接从构造函数返回句柄的尝试失败。但是,在创建实例之后,可以从类方法或从class(?)方法获得成功。这是类定义和示例脚本<?php
class HMMDatabaseHandle {
private static $configfile = "config.json";
// uncomment for test 1
// public function __construct () {
// return self::get_handle_admin();
// }
public static function create() {
return self::get_handle_admin();
}
private static function get_handle_admin() {
$config = json_decode(file_get_contents(self::$configfile));
$dbhost = $config->database->dbhost;
$dbname = $config->database->dbname;
$dbuser = $config->database->dbuser;
$dbpass = $config->database->dbpass;
try {
return new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
}
?>
这是我正在使用的测试脚本:<?php
require_once 'HMMDatabaseHandle.php';
// Test 1 - fails (uncomment constructor func) at call to prepare() with:
// PHP Fatal error: Call to undefined method HMMDatabaseHandle::prepare()
//$dbh = new HMMDatabaseHandle();
// Test 2 - works when class creates default constructor
// i.e. no explicit __construct() func
// Fetching data from executed query is fine
//$db = new HMMDatabaseHandle();
//$dbh = $db->create();
// Works using static class methods rather than instance
$dbh = HMMDatabaseHandle::create();
$sth = $dbh->prepare('select data_title,track_id from master');
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
...
}
我的问题是:当看上去与直接调用类方法非常相似时,为什么不能直接从构造函数返回句柄?为什么构造函数调用类方法还是我的脚本调用它很重要?
如果我使用PHP的默认构造函数创建实例,我真的使用$ db-> create()调用类方法吗?
我似乎在这里缺少一些基本概念。预先感谢!