Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

PHP type self

Within a class, self in a type declaration refers to the declaring class.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

public static function make(): self

Within a class, self in a type declaration refers to the declaring class. A subclass instance satisfies that type as well. In an inherited factory, constructing new self creates the class where the method was defined even when the caller names a subclass. Use this distinction when selecting a factory return contract.

class Note { public static function make(): self { return new self(); } }
class Memo extends Note {}
echo json_encode([get_class(Note::make()), get_class(Memo::make())]);
["Note","Note"]

Examples

<?php
class Note { public static function make(): self { return new self(); } }
class Memo extends Note {}
echo json_encode([get_class(Note::make()), get_class(Memo::make())]);

Result

["Note","Note"]

Sources