When would you use the $this
keyword in PHP? From what I understand $this
refers to the object created without knowing the objects name.
Also the keyword $this
can only be used within a method?
An example would be great to show when you can use $this
.
$this is a reserved keyword in PHP that refers to the calling object. It is usually the object to which the method belongs, but possibly another object if the method is called statically from the context of a secondary object. This keyword is only applicable to internal methods.
The use is necessary for your controller to be able to use ImageRepository . Once it is loaded into your object in the constructor with $this->image = $imageRepository; , your controller methods have access to its methods, (such as upload ) via $this->image .
Definition and Usage The extends keyword is used to derive a class from another class. This is called inheritance. A derived class has all of the public and protected properties of the class that it is derived from.
$this means the current object, the one the method is currently being run on. By returning $this a reference to the object the method is working gets sent back to the calling function.
A class may contain its own constants, variables (called "properties"), and functions (called "methods").
<?php
class SimpleClass
{
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar() {
echo $this->var;
}
}
?>
Some examples of the $this pseudo-variable:
<?php
class A
{
function foo()
{
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")\n";
} else {
echo "\$this is not defined.\n";
}
}
}
class B
{
function bar()
{
// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
}
}
$a = new A();
$a->foo();
// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
$b = new B();
$b->bar();
// Note: the next line will issue a warning if E_STRICT is enabled.
B::bar();
?>
The above example will output:
The most common use case is within Object Oriented Programming, while defining or working within a class. For example:
class Horse {
var $running = false;
function run() {
$this->running = true;
}
}
As you can see, within the run
function, we can use the $this
variable to refer to the instance of the Horse class that we are "in". So the other thing to keep in mind is that if you create 2 Horse classes, the $this
variable inside of each one will refer to that specific instance of the Horse class, not to them both.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With