0

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!

1
  • First of all, I'd order the classes correctly (it will make sense more after you do that). The value of $this is of class 'A'. Commented Jun 5, 2012 at 6:44

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You're correct. It's inheritance 101. I just wanted to mention that there's a function called get_parent_class which can be used to determine the class of the parent class if necessary.
0

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().

1 Comment

I updated my question, I am not calling it in class context, but in function context.
-1

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.

2 Comments

Yes, its a self reference, so why is $this not the type of the class I am actually in?
This does not answer the original posters question, does it?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.