Reputation: 137
I code something like this to give you an example
This is using "$this->"
<?php
class A{
public function example(){
echo "A";
}
}
class B extends A{
public function example2(){
$this->example();
}
}
$b = new B();
echo $b->example2();
?>
and This is using parent::
<?php
class A{
public function example(){
echo "A";
}
}
class B extends A{
public function example2(){
parent::example();
}
}
$b = new B();
echo $b->example2();
?>
What is different between $this-> and parent:: in OOP PHP?
Upvotes: 7
Views: 3987
Reputation: 2927
In simple words
$this is an instance reference, so whenever you use $this it starts referencing current class methods and properties.
parent is a parent reference which can be used to access parent class properties and methods with public or protected access modifier.
Upvotes: 3
Reputation: 2412
parent::example()
calls the parent class method, where $this->example()
call the current class method.
In your example there's no difference, since class B
doesn't override example()
method. It is common to write something like this (maybe it will help you to understand better this concept):
class A {
public function example(){
echo 'A';
}
}
class B extends A {
public function example(){
echo 'B';
}
public function example2(){
$this->example();
}
public function example3() {
parent::example();
}
}
$b = new B();
$b->example2();//print B
$b->example3();//print A
Upvotes: 6
Reputation: 366
parent::
will call a method or an attribute of the parent. However, since this is refering to the class and not any kind of instance, you can only call a static method or attribute.
$this->
refers to the current instance of the object you call this in.
You could also want to refer to self::
which refers to the current class (once again, no instance involved here) within an object or a static method.
Upvotes: 0
Reputation: 47945
The difference is that you can access a function of a base class and not of the currient implementation.
class A {
public function example() {
echo "A";
}
public function foo() {
$this->example();
}
}
class B extends A {
public function example() {
echo "B";
}
public function bar() {
parent::example();
}
}
And here some tests:
$a=new A();
$a->example(); // echos A
$a->foo(); // echos A
$b=new B();
$b->example(); // echos B
$b->foo(); // echos B
$b->bar(); // echos A
Upvotes: 12