php - 注册表 Php 示例

标签 php design-patterns registry

我有这段代码,是我在阅读时遇到的,当我在浏览器中查看它时,它不会导致任何错误。我的问题是类如何在没有设置属性的情况下调用 $this->registry。换句话说,函数中的 $this->registry 指的是什么?

class Template{

public function __construct($registry){
    $this->registry = $registry;
}

这就是我实例化类的方式。

<?php
include 'registry.class.php';
include 'template.class.php';
$registry = new Registry();
$template = new Template($registry);
?>

最佳答案

您基本上是在引用 Registry 对象。这样看:

function __construct(Registry $registry) {
    $this->registry = $registry;
}

引用 $this->registry 是调用 Registry 对象的 Templates“副本”。因此,当您将 $registry 对象传递给 Template 时:

$template = new Template($registry); 

您基本上是在“赋予”模板类它自己的 $registry 对象。 我以前使用过类似的注册表。你可以在哪里实例化它:

$registry = new registry();
$registry->template = new template($registry);

允许您通过注册表访问模板方法/变量/等:

$registry->template->method();

会有人比我现在能更好地解释发生的事情很多,但请记住,最好的学习方法是反复试验。从错误中吸取教训:-)


根据评论,您的 Template 类应该如下所示:

class Template {

    var $registry;

    function __construct($registry) {
        $this->registry = $registry;
    }
}

这将允许您在整个类里面访问它。

例子:

function link($url){
    return $this->registry->site->link($url);
}

以上是一个虚构的函数,对网站的引用也是虚构的,但展示了如何使用此类和/或注册表。

关于php - 注册表 Php 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24987243/

相关文章:

php - mysql保存用户名字符串类似时间戳的数据类型

php - Codeigniter 允许在插入查询中使用单引号

java - 那里有任何 Java 享元模式实现吗?

c++ - 如何从 32 位代码启动 64 位 Windows 进程?

batch-file - 批处理文件 : If registry key's data is equal to

javascript - 如何在 JavaScript 中验证输入?

php - 如何在 smarty 模板文件中分配数组?

java - 母厂内有多个工厂

c# - 桌面应用程序可能的数据访问层设计模式是什么?

C# : Switch between power plans