Strange result using instance methods in PHP 5.3

It is amazing how the example below actually works, and how one could do something like dynamically. Using call_user_func or call_user_func_array does not allow this to happen.

 <?php class Person { public $name = "George"; public function say_hi() { return ExtraMethods::hi(); } } class ExtraMethods { public function hi() { return "Hi, ".$this->name; } } $george = new Person(); echo $george->say_hi(); ?> 

this should be the result of:

 Hi, George 

I wonder why the hi instance method can be called not only statically (not surprised that this can happen in PHP), but also why I can use $this

+4
source share
1 answer

From manual :

The pseudo-variable $ this is available when the method is called from the context of the object. $ is a reference to the calling object (usually the object to which the method belongs, but possibly another object if the method is called statically from the context of the secondary object).

So, according to the second part, by design. Keep in mind that it uses the actual instance of the object in reality (in other words, if you add public $name = "SomethingElse"; in ExtraMethods , the result will be Hi, George ).

The method call statically is incorrect coding, but PHP forgives you and gives only a severe error:

 "Strict Standards: Non-static method ExtraMethods::hi() should not be called statically, assuming $this from incompatible context in ..." 

Of course, in this case, just passing the object as an argument will be much clearer and preferable.

+4
source

Source: https://habr.com/ru/post/1390714/


All Articles