V
V
Valery Rusin2012-11-29 11:44:00
PHP
Valery Rusin, 2012-11-29 11:44:00

Incomprehensible behavior when calling a method

class A {

  public $a = 2;
  
  public function checkVar()
  {
    var_dump($this);
  }

}

class B {
  
  public $b = 10;

  public function test()
  {
    A::checkVar();
  }
}

$b = new B;
$b->test();


I looked at the documentation, but did not understand. Why is $this an object B in this case?
The question is purely out of curiosity.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
U
Urvin, 2012-11-29
@Urvin

The lack of extends for B or static for A is confusing. PHP is also confusing.

S
Sergey Beresnev, 2012-11-30
@sectus

The heavy legacy of PHP4. I found it myself by accident when here the dude showed his code in questions. But I never found a mention of this thing in the documentation, only in bugs that this is a feature .
And it turns out that already in PHP4 it was possible to use something similar to traits :).

V
Vyacheslav Plisko, 2012-11-29
@AmdY

You can't use $this in a static method because it's a class method, not an object method.
The same magic with the presence of $this is a relic of the past, when in php 4 OOP was screwed through a crutch and there was no difference between calling a static method and an object method. The word static did not seem to exist at all in the context of that OOP.

L
loingrim, 2012-11-29
@loingrim

Why B is issued is more or less clear. You call A::checkVar() as a static method of class A. Accordingly, it is called in the context of object B, and $this refers to the current context. When you call a static class method, the object is not created, so it doesn't have any $this.
www.php.net/manual/en/language.oop5.basic.php#language.oop5.basic.class.this
If you want to get A, then you need to do $a = new A(); $a->checkVar();

M
m1z0, 2012-11-29
@m1z0

because class B is defined and A is called from B, especially by a static method, then it will display information about class B (as far as I understand the problem).
If extends from B, then it will display information about both classes (I can be wrong)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question