Rio Eduardo Rio Eduardo - 7 months ago 9
PHP Question

What is different between $this-> and parent:: in OOP PHP?

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?

Answer

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