调用一个类方法的公共构造函数和调用另一个类方法的一个类方法之间有什么区别?

问题描述 投票:-1回答:1

我对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)) {
   ...
}

我的问题是:

  1. 当看上去与直接调用类方法非常相似时,为什么不能直接从构造函数返回句柄?为什么构造函数调用类方法还是我的脚本调用它很重要?

  2. 如果我使用PHP的默认构造函数创建实例,我真的使用$ db-> create()调用类方法吗?

我似乎在这里缺少一些基本概念。预先感谢!

php class constructor class-method
1个回答
0
投票

您无法在该上下文中从构造函数返回句柄,因为这将违反new的已定义行为。 new只会返回该类的实例,而不管构造函数中调用了什么其他方法。

new SomeClass();是空方法。返回<< 1>并非打算

。这并不意味着其中的其他代码不会被执行,只是在创建新对象的上下文中忽略了您的__construct()

1

可以实际显式调用__construct()方法之后创建对象,然后它将像普通方法一样工作,并且您的return将起作用。__construct()
尽管这不是正常的事情,但我无法想到一个有用或可取的方案。我只想指出这是可能的。
© www.soinside.com 2019 - 2024. All rights reserved.