Reputation: 31
I have this code which I came across in reading and when I view it in a browser it does not cause any errors. My question is how can the class call $this->registry
without the property being set. In other words what is the $this->registry
within the function referring to?
class Template{
public function __construct($registry){
$this->registry = $registry;
}
}
this is how I instantiate the classes.
<?php
include 'registry.class.php';
include 'template.class.php';
$registry = new Registry();
$template = new Template($registry);
?>
Upvotes: 3
Views: 447
Reputation: 13128
You're basically referencing the Registry
object. Look at it this way:
function __construct(Registry $registry) {
$this->registry = $registry;
}
Referencing $this->registry
is calling the Templates
"copy" of the Registry
object. So when you pass the $registry
object to the Template
with:
$template = new Template($registry);
You're basically "giving" the Template class its own $registry
object.
I've used a similar registry before. Where you can instantiate it like this:
$registry = new registry();
$registry->template = new template($registry);
Allowing you to access Template methods/vars/etc via the registry:
$registry->template->method();
There will be somebody who can explain the exact happenings a lot better than I can right now, but remember, the best way to learn is by trial and error. Learn from your mistakes :-)
As per the comments, your Template
class should look like this:
class Template {
var $registry;
function __construct($registry) {
$this->registry = $registry;
}
}
That will allow you to access it throughout the class.
Example:
function link($url){
return $this->registry->site->link($url);
}
The above is a fictional function and the reference to site is also fictional but shows how you could use this class and/or registry.
Upvotes: 1
Reputation: 51
->
is for accessing object fields. So you are setting an object field called registry in the constructor for Template to the value of $registry, which is passed to the constructor. Think for this->registry
as referring to a variable registry
in the object Template
.
Upvotes: 0