EOB
EOB

Reputation: 3085

Inheritance and PHP - what is "this" after call of parent?

I have this scenario:

class A extends B {
   public function test() {
       parent::test();
   }
}

class B extends someCompletelyOtherClass {
   public function test() {
       //what is the type of $this here?
   } 
}

What is the type of $this in class B in function test? A or B? I tried and its A, I was thinking its B? Why is it A?

Thanks!

Upvotes: 0

Views: 73

Answers (3)

harald
harald

Reputation: 6126

I'm not a PHP expert, but I think this makes sense. $this should point to the instantiated object which is of type A, even if the method is defined in class B.

If you make an instance of class B and call it's test method directly, $this should point to an object of type B.

Upvotes: 2

Adelin
Adelin

Reputation: 19011

In PHP, the keyword “$this” is used as a self reference of a class and you can use it for calling and using the class functions and variables. and here is an example:

class ClassOne
{
    // this is a property of this class
    public $propertyOne;

    // When the ClassOne is instantiated, the first method called is
    // its constructor, which also is a method of the class
    public function __construct($argumentOne)
    {
        // this key word used here to assign
        // the argument to the class
        $this->propertyOne = $argumentOne;
    }

    // this is a method of the class
    function methodOne()
    {
        //this keyword also used here to use  the value of variable $var1
        return 'Method one print value for its '
             . ' property $propertyOne: ' . $this->propertyOne;
    }
}

and when you call parent::test() you actually calling the test function associated with the CLASS B since you are calling it statically. try call it $this->test() and you should get A not B.

Upvotes: -1

Emil Vikström
Emil Vikström

Reputation: 91983

The problem is that you are calling test() statically, i.e., in class context. It's an error to call non-static functions statically (PHP does not enforce this, unfortunately).

You should use $this->test(), not parent::test().

Upvotes: 0

Related Questions