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());
?>
PHP.mk документација
Релативни типови на класи
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
Патека
language.types.relative-class-types.php
Локална патека за оваа страница.
Извор
php.net/manual/en
Оригиналниот HTML се реупотребува и локално се стилизира.
Режим
Прокси + преведен приказ
Кодовите, табелите и белешките остануваат читливи во истиот тек.
Референца
language.types.relative-class-types.php
Релативни типови на класи
Референца за `language.types.relative-class-types.php` со подобрена типографија и навигација.
Релативни типови на класи
Овие декларации за тип може да се користат само во класи.
self
Вредноста мора да биде instanceof истата класа како онаа во која се користи декларацијата за тип.
parent
Вредноста мора да биде instanceof родител на класата во која се користи декларацијата за тип.
static
static е тип само за враќање што бара вредноста што се враќа да биде instanceof истата класа како онаа во која се повикува методот. Достапно од PHP 8.0.0.
Белешки од корисници 1 белешка
постојани врски ¶
1 месец пред