dpd66100 2011-03-24 12:05
浏览 23
已采纳

PHP全局对象

I have a Singleton pattern Database object which I would like to declare once for use within the system. I have a main include file which serves up all of the separate class files and also makes some global variables.

Here's the include file:

<?php
// Main API. We want to include everything here and then make some Global Vars:
require_once('database.class.php');

// Create the DB here:
$database = Database::Singleton();

require_once('user.class.php');
require_once('settings.class.php');

// Start the session:
session_start();
?>

In theory, $database should be a global variable accessible by anything included thereafter (i.e. user.class.php and settings.class.php. However, when I try to call a method in the Database class from the User class as follows:

$result = $database->FetchObject($queryString);

I get the following error:

Fatal error: Call to a member function NumRows() on a non-object in C:\Program Files (x86)\EasyPHP-5.3.4.0\www\PC Estimating\classes\user.class.php on line 122

Is anyone able to help?

  • 写回答

2条回答 默认 最新

  • dtpk04526211 2011-03-24 12:08
    关注

    If you are trying to use the $database object from inside a method of a class, you must use the global keyword, so the $database variable is visible from the method :

    class User {
        function myMethod() {
            global $database;
    
            // Work with $database
    
        }
    }
    


    For more informations, take a look at the Variable scope section of the manual.


    Another (better) solution, considering you are use a singleton, would be to get that object from the singleton :

    class User {
        function myMethod() {
            $database = Database::Singleton();
    
            // Work with $database
    
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么