Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 739
Rio Eduardo Avatar asked Dec 01 '22 19:12

Rio Eduardo


1 Answers

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
like image 128
rekire Avatar answered Dec 27 '22 04:12

rekire