Reputation: 163
I understand the official explanation about the $this: http://php.net/manual/en/language.oop5.basic.php
But if I try to understand what is the object reference in this case of symfony, I don't know who is it, for example:
Each time when you need to return the theme, use this:
public function indexAction()
{
return $this->render('foo/bar.html.twig', array());
}
Or when you generate a some form:
public function indexAction(Request $request)
{
// Create the form
$form = $this->createFormBuilder()
->add('name', TextType::class)
->add('email', EmailType::class)
->add('subject', TextType::class)
->add('message', TextareaType::class)
->add('send', SubmitType::class)
->getForm();
}
But who is exactly the object $this? and if working with other word or value that is not $this, only for try to understand better.
Upvotes: 0
Views: 303
Reputation: 13167
If you are asking where are located the methods called by $this
in your controller, take a look at the extends
statement of your controller (just after class declaration).
All your controllers extends (by default) the FrameworkBundle Controller, also you can access all of the inherited methods, such as createForm
, render
, getDoctrine
, generateUrl
.
The parent Controller
extends from ContainerAware
(Dependency Injection), it allows you to access and use services
.
Most of the methods I listed are just shortcuts of services methods.
i.e. $this->generateUrl(/*params*/)
is equal to $this->container->get('router')->generate(/*params/*)
Upvotes: 1
Reputation: 102001
$this
is how instances of a class in refer to themselves in PHP.
class Person
private $name;
public function __construct($name){
$this->name = $name;
}
public function getName($name){
$this->name = $name;
}
end
When you create a instance of the class with $foo = new Person('Max');
. $this
referrers to the new instance you are creating. When you use $this
in a controller - this refers to the controller itself.
In natural language its like saying my
.
Upvotes: 0
Reputation: 500
In that case $this references an instance of the object eg. you are in a controller, then the $this variable references the current instance of the controller that you are in, and you can access all the methods that the class itself has and all the methods of the extended class in this case the base controller and so on in the inheritance hierarchy.
You can read this question to get more clarity.
How does the "this" keyword work?
Upvotes: 0