PHP: rewriting static methods does not work properly

I have two php classes: TestUK and TestFR, which extend TestUK.

Both classes are used to generate requests for two different domains. But something is wrong with the inheritance, and I do not understand why.

I have one method called "get_domain" that is being rewritten to get the domain that should really be used. If I call it directly through TestFR::get_domain() , I get the expected result. But if I call a method that is not overwritten by TestFR, but which uses self::get_domain() , I get the wrong domain.

If I just copy and paste the do_stuff method from TestUK to TestFR, then I get the expected result. But copying the same (!) Code is what I tried to avoid.

What is the reason for this? I don't have much experience with class inheritance in PHP, but I expected this to work without problems. Or is my failure completely ruined?

 <?php class TestUK { const DOMAIN_UK = 'http://www.domain.co.uk'; const DOMAIN_FR = 'http://www.domain.fr'; static function get_domain(){ return self::DOMAIN_UK; } static function do_stuff(){ echo self::get_domain(); } } class TestFR extends TestUK { static function get_domain(){ return self::DOMAIN_FR; } } // Works as intended: // Expected and actual output: http://www.domain.fr echo TestFR::get_domain(); // Does NOT work as intendes: // Expected Output: http://www.domain.fr // Actual Output: http://www.domain.co.uk TestFR::do_stuff(); ?> 
+6
source share
2 answers

This is because the self keyword refers to the class where it appears, and not to the class on which the method was called. For the last function, you will have to use late static binding with the static :

 static function do_stuff(){ echo static::get_domain(); } 

However, this code smells a lot. Why is everything static and not just an instance method? Why is TestFR extending TestUK instead of extending the abstract base class Test ?

Would be better convert everything to non-static methods, and as a bonus, your problem will disappear right away.

+15
source

name it (if you use php> = 5.3

 static::get_domain(); 
+1
source

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


All Articles