drsl90685154 2015-03-20 01:13
浏览 48
已采纳

在PHP MVC中访问单例数据库对象时遇到问题

I am having trouble on accessing to an instance of a singleton class in PHP MVC. Basically the MVC looks like

enter image description here

First of all I have included and instantiated objects in the init.php as

// include objects
include('app/Database.php');
include('app/models/m_template.php');
include('app/models/m_categories.php');

// create objects
$tdatabase = new Database();
$Template = new Template();
$Categories = new Categories();

and in m_categories.php I tried to use the $tdatabase object as:

<?php

class Categories {

    private $db_table = 'category';

    function __construct() { }

    public function get_categories() {
        $data = array();
        $res = $tdatabase->query("SELECT * FROM " . $this->db_table . " ORDER BY name");

        foreach ($res as $dataRow):
            $data[] = array('id' => $dataRow['id'],
                'name' => $dataRow['name'],
                'img' => $dataRow['img'],
                'alt' => $dataRow['alt'],
            );

        endforeach;
        return $data;
    }
}

and finally in index.php I have:

<?php
include('app/init.php');

echo '<pre>';
 print_r($Categories->get_categories());
echo '</pre>';

but I am getting following errors:

enter image description here

can you please let me know why this is happening and how I can fix this?

Update 1:

enter image description here

Update 2

enter image description here

  • 写回答

2条回答 默认 最新

  • dseomy1964 2015-03-20 01:25
    关注

    Categories object doesn't have any information about outside variables. You sholud pass Database object to your Categories object e.g. by constructor or by method parameter.

    init.php

    $tdatabase = new Database();
    $Template = new Template();
    $Categories = new Categories($tdatabase);
    

    m_categories.php

    class Categories {
        protected $database;
        private $db_table = 'category';
    
        function __construct($database) {
             $this->database = $database;
        }
    
        public function get_categories() {
            $data = array();
            $res = $this->database->query("SELECT * FROM " . $this->db_table . " ORDER BY name");
            // (...)
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢