| Newsgroups |
php.notes |
| Message-ID |
<[email protected]> |
The documentation says that :
"self" is an instanceof the same class as the one in which the type declaration is used.
while "static" is an instanceof the same class as the one the method is called in.
But it does not provide an example, and here I want to provide an example,
We have 2 classes, the first one is "A", and the second is "B". Let us declare 2 methods in the class "A" that use "self" and "static", then we will make "B" extend the "A" class, and then call the methods from "B" and "A", then compare.
example :
<?php
class A
{
public static function withSelf(): self
{
return new self();
}
public static function withStatic(): static
{
return new static();
}
}
class B extends A {}
// output: A
// returns the class "A" because we called the method from the same class
// where the method is declared
var_dump(A::withSelf());
// output: A
// but here also returns "A" because, as the documentation says:
// "self" is an instanceof the same class as the one in which the type declaration is used.
var_dump(B::withSelf());
// output: A
// returns the class "A" because we called the method from the same class
// where the method is declared
var_dump(A::withStatic());
// output: B
// but here also returns "B" because, as the documentation says:
// "static" is an instanceof the same class as the one the method is called in.
var_dump(B::withStatic());
?>
----
Server IP: 206.189.2.9
Probable Submitter: 2001:16a2:f552:6700:25e6:dc9d:89ed:aa62
----
Manual Page -- https://php.net/manual/en/language.types.relative-class-types.php
Edit -- https://main.php.net/note/edit/130659
Del: integrated -- https://main.php.net/note/delete/130659/integrated
Del: useless -- https://main.php.net/note/delete/130659/useless
Del: bad code -- https://main.php.net/note/delete/130659/bad+code
Del: spam -- https://main.php.net/note/delete/130659/spam
Del: non-english -- https://main.php.net/note/delete/130659/non-english
Del: in docs -- https://main.php.net/note/delete/130659/in+docs
Del: other reasons-- https://main.php.net/note/delete/130659
Reject -- https://main.php.net/note/reject/130659
Search -- https://main.php.net/manage/user-notes.php