Search code examples
phptraitsreturn-typefluent

Return "self" for the return type of a function inside a PHP trait


In a PHP trait, can I use self as the return type of a method? Will it reference the class that imports the trait?

<?php

declare(strict_types=1);

trait MyTrait
{

    public function setSomething(array $data): self
                                             // ^ is this ok?
    {
        $this->update($data);
        return $this;
    }
}

Solution

  • In fact this is the ONLY thing you can do (referring to the instance or class).

    class TestClass {
        use TestTrait;
    }
    
    trait TestTrait {
        public function getSelf(): self {
            echo __CLASS__ . PHP_EOL;
            echo static::class . PHP_EOL;
            echo self::class . PHP_EOL;
    
            return $this;
        }
    }
    
    $test = new TestClass;
    var_dump($test->getSelf());
    

    Output

    TestClass
    TestClass
    TestClass
    object(TestClass)#1 (0) {
    }
    

    Working example.