I have a class Page that creates an instance of DB, which is named $db.

我有一个创建DB实例的类Page,名为$ db。

In the __construct() of Page, I create the new $db object and I pull a bunch of config data from a file.

在Page的__construct()中,我创建了新的$ db对象,并从文件中提取了一堆配置数据。

Now the DB class has a method _connectToDB() which (attempts) to connect to the database.

现在,DB类有一个方法_connectToDB(),它(尝试)连接到数据库。

Is there a way in the DB class to call the parent class's config array? I don't want to make global variables if I don't have to and I don't want to grab the config data twice.

DB类中有没有办法调用父类的配置数组?如果我不需要,我不想创建全局变量,我不想两次获取配置数据。

Pseudo code might look something like this...

伪代码可能看起来像这样......

$dbUsername = get_calling_class_vars(configArray['dbUserName']);

6 个解决方案

#1


6

I find that it's often easier to initialise all the "important" objects close to whatever variables they need to know. You could try it this way:

我发现通常更容易初始化所有“重要”对象,接近他们需要知道的任何变量。你可以这样试试:

/* Code to get config variables here */
$DB = new DB($config);
/* You might want to delete the database password from $config here */
$Page = new Page($config, $DB);

Doing it this way means you can also do type-checking on the database object if you want to:

这样做意味着您还可以对数据库对象进行类型检查,如果您想:

class Page {
    function __construct(array $config, DBClass $db) { }
}

更多相关文章

  1. 传入连接对象或在类中创建它? (OOP)
  2. 在MySQL数据库中搜索与多个Tag记录相关/包含的书签
  3. 使用jquery和php手动在数据库中增加一个字段[复制]
  4. 当将带有撇号的单词保存到数据库时,mysql_real_escape_string会添
  5. php扫马、内网查mysql数据库账号密码(内网webshell渗透)
  6. thinkphp5 数据库和模型详解 之1 数据库基础
  7. Wordpress查询另一个wordpress数据库for循环
  8. CakePHP2 Request请求对象中文教程
  9. 电商网站项目总结(面向对象编程篇)

随机推荐

  1. C#连接Oracle的实例教程
  2. 实现一个验证码生成类(含数字,拼音,汉字)
  3. SignalR Self Host多端消息推送服务实例(
  4. ASP.NET Core简单介绍教程(1)_实用技巧
  5. 带你掌握OOM框架AutoMapper使用实例
  6. SignalR Self Host多端消息推送服务介绍(
  7. ASP.NET Core环境设置教程(2)_实用技巧
  8. 详解关于Blog实现一个日历的实例教程
  9. ASP.NET中的参数与特殊类型的实例详解
  10. ASP.NET Core新建项目教程(3)_实用技巧