PHP: Is it possible to get the name of the class using the trait from within a trait static method?

Use late static binding with static:

trait SomeAbility {
    public static function theClass(){
        return static::class;
    }
}

class SomeThing {
    use SomeAbility;
}

class SomeOtherThing {
    use SomeAbility;
}

var_dump(
    SomeThing::theClass(),
    SomeOtherThing::theClass()
);

// string(9) "SomeThing"
// string(14) "SomeOtherThing"

https://3v4l.org/mfKYM


Yep, using the get_called_class()

<?php
trait SomeAbility {
    public static function theClass(){
        return get_called_class();
    }
}

class SomeThing {
    use SomeAbility;
}
// Prints "SomeThing"
echo SomeThing::theClass();

You can call get_class() without a parameter to get the name of the current class...

trait SomeAbility {
    public static function theClass(){
        return get_class();
    }
}

class SomeThing {
    use SomeAbility;
}

echo SomeThing::theClass().PHP_EOL;

Tags:

Php

Traits