【发布时间】:2020-02-19 19:42:17
【问题描述】:
我对 OO 编程有点陌生,无法理解为什么一种机制有效而另一种机制无效。
我创建了一个返回 MySQL 数据库句柄的简单类。我尝试直接从构造函数返回句柄失败。但是在创建实例后从类方法或类(?)方法成功。这是类定义和示例脚本
<?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() 调用一个类方法吗?
我似乎在这里遗漏了一些基本概念。提前致谢!
【问题讨论】:
-
类构造函数返回新创建的对象——没有别的。嗯,这并不完全正确。
new关键字实际上返回了它,但构造函数通常与它一起使用,这使得构造函数似乎正在返回它。您可以将 __construct 函数视为在实例化类时执行某些代码的地方。它实际上没有返回任何内容/void。
标签: php class constructor class-method