PHP:如何在类中正确创建类的实例?(AKA 使用类中的类)


PHP: How to properly create an instance of a class within a class? (AKA use a class within a class)

我读到在另一个类(html class)中使用类属性(database class)的最佳方法是在类(html)中创建该类的实例。至于为什么,我不确定...但无论如何。

这是怎么做到的?我有两种情况,看看哪些是正确的,哪些是错误的......

方案 A

require( database.php );
class html(){
    private static $db = null;
    private static $page = null;
    public function __construct($id){
        self::bootstrap($id);
    }
    public static function bootstrap($id){
        self::$db = new database();
        self::$page = $db->page($id);
        return self::$page;
    }
}
//$page = new html('hello-world');
//print $page;
print html::bootstrap('hello-world');

方案 B

//Class autoloader
spl_autoload_register(function ($class) {
    include $_SERVER['DOCUMENT_ROOT'] . '/class/' . $class . '.php';
});

//Scenario B code
class html(){
    private static $page = null;
    public static function bootstrap($id){
        self::$page = database::page($id);
        return self::$page;
    }
}
print html::bootstrap('hello-world');

也许您有不同的合适的方案,如果这些是错误的方法

我会说没有场景是错误的,但场景B更合适。由于page在类中被设计为静态方法database因此通知了该方法的有意使用。