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 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line