简体   繁体   中英

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?

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

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM