-1

I am learning Classes and Objects of PHP, but these codes confuses me:

<?php
class A
{
    public function test()
    {
        //output will be A load(), why?
        self::load();
        //output will be B load(), why?
        $this->load();
    }
    public function load()
    {
        echo "A load()";
    }
}

class B extends A
{
    public function test()
    {
        parent::test();
    }
    public function load()
    { 
        echo "B load()";
    }
}
$c  = new B();
$c->test();

In these situation, why self::load() and $this->load() get different output?

Please describe with detail.

FisherMartyn
  • 826
  • 1
  • 8
  • 17
  • Possible duplicate of [When to use self over $this?](http://stackoverflow.com/questions/151969/when-to-use-self-over-this) – mitkosoft Mar 01 '16 at 08:20
  • because `self::load()` references the `load()` method of the __class where the method is called__ in the inheritance tree; whereas `$this->load()` references the load method of the __instance__, and by inheritance the `B` `load()` method is overriding the `A` `load()` method for the instance – Mark Baker Mar 01 '16 at 08:20

2 Answers2

5

It's because self use the class it belongs to as it was defined. The whole thing is documentationed here: http://php.net/manual/en/language.oop5.late-static-bindings.php

There is a different between using self and static. Be aware with your code, normally the method test needs to be defined as static for calling it with self::test();.

SebTM
  • 370
  • 1
  • 10
0

so lets start.

Self choose current class.

this chose current object.

so when you use self::load(); it load function in class A

in the other hand when you use $this->load(); it mean class B->load