Answer the question
In order to leave comments, you need to log in
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();
Answer the question
In order to leave comments, you need to log in
The lack of extends for B or static for A is confusing. PHP is also confusing.
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 :).
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.
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();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question