PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 26, 2022

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

 October 26, 2022     inheritance, oop, php, super     No comments   

Issue

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?


Solution

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


Answered By - rekire
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing