|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2016-06-24 12:16 UTC] cmb@php.net
-Status: Open
+Status: Duplicate
-Assigned To:
+Assigned To: cmb
[2016-06-24 12:16 UTC] cmb@php.net
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Nov 03 20:00:02 2025 UTC |
Description: ------------ If you want to build a function that force to return its own instance, you simply set it as returning self. But when you want to extend it, then PHP will said that our new class is not compatible with the parent one if we are overloading it. So maybe the "static" keyword is the answer, as it will be evaluated when executing? Wrong, PHP does not except the "static" keyword. This problems are the same for both class inheritance and interface implementation. Test script: --------------- // Interfaces // Sample 1 // with "self" keyword interface MyInterface { public function myFunction(): self; } class MyClass implements MyInterface{ public function myFunction(): self { return $this; } } // Fatal error: Declaration of MyClass::myFunction(): MyClass must be compatible with MyInterface::myFunction(): MyInterface // Sample 2 // with "static" keyword interface MyInterface { public function myFunction(): static; } class MyClass implements MyInterface { public function myFunction(): static { return $this; } } // Parse error: syntax error, unexpected 'static' (T_STATIC) // Classes and inheritance // Sample 3 // with "self" keyword class MyClass { public function myFunction(): self { return $this; } } class MyClass2 extends MyClass { public function myFunction() : self { return $this; } } // Fatal error: Declaration of MyClass2::myFunction(): MyClass2 must be compatible with MyClass::myFunction(): MyClass // Sample 4 // with "static" keyword class MyClass { public function myFunction(): static { return $this; } } class MyClass2 extends MyClass { public function myFunction(): static { return $this; } } // Parse error: syntax error, unexpected 'static' (T_STATIC) Expected result: ---------------- I think that the "self" keyword should work, as MyClass implements MyInterface (or MyClass2 extends MyClass), so the first one is an instance of the second one. Anyway, we can imagine that my asumption is false. So why that "static" word would not work here?