PHP: 是否可以使用特征静态方法中的特征获取 class 的名称?

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

可以从属于该特征的静态方法中确定使用特征的 class 的名称吗?

例如:

trait SomeAbility {
    public static function theClass(){
        return <name of class using the trait>;
    }
}

class SomeThing {
    use SomeAbility;
    ...
}

获取 class 的姓名:

$class_name = SomeThing::theClass();

我的直觉是,可能不会。我没能找到任何其他建议。

使用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

是的,使用 get_called_class()

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

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

您可以不带参数调用get_class()来获取当前class...

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

class SomeThing {
    use SomeAbility;
}

echo SomeThing::theClass().PHP_EOL;

self::class === get_class()

静态::class === get_called_class()

<?php

    trait MyTrait
    {
        public function getClasses()
        {
            return [self::class, static::class];
        }
    }
    
    class Foo
    {
        use MyTrait;
    }
    
    class Bar extends Foo
    {
    }
    
    var_dump((new Foo)->getClasses());
    
    var_dump((new Bar)->getClasses());

会return

array (size=2)
  0 => string 'Foo' (length=3)
  1 => string 'Foo' (length=3)
array (size=2)
  0 => string 'Foo' (length=3)
  1 => string 'Bar' (length=3)