注册表Php示例


Registry Php Example

我有这段代码,我在阅读中遇到,当我在浏览器中查看它时,它不会导致任何错误。我的问题是类如何在没有设置属性的情况下调用$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调用TemplatesRegistry对象的"副本"。所以当你用

$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);
}

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

->用于访问对象字段。因此,在Template的构造函数中将一个名为registry的对象字段设置为传递给构造函数的$registry的值。考虑this->registry引用对象Template中的变量registry