parent, self, static

Bu türlerin bildirimleri yalnızca sınıfların içinde kullanılabilir.

self

Bu türden bir nesne, tür bildiriminin kullanıldığı sınıfın örneği (instanceof) olmalıdır.

parent

Bu türden bir nesne, tür bildiriminin kullanıldığı sınıfın ebeveyninin örneği (instanceof) olmalıdır.

static

static, döndürülen nesnenin yöntemin çağrıldığı sınıfın örneği (instanceof) olmasını gerektiren dönüş türüdür. PHP 8.0.0 ve sonrasında kullanılabilir.

add a note

User Contributed Notes 1 note

up
1
mrmhmdalmalki at gmail dot com
10 days ago
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());

?>
To Top