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

时间:2018-05-18 08:56:20

标签: php traits

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

例如:

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

class SomeThing {
    use SomeAbility;
    ...
}

获取课程名称:

$class_name = SomeThing::theClass();

我的预感是,可能不是。我无法找到任何其他暗示的东西。

4 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

是的,使用get_called_class()

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

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

答案 2 :(得分:1)

您可以在没有参数的情况下调用get_class()来获取当前类的名称...

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

class SomeThing {
    use SomeAbility;
}

echo SomeThing::theClass().PHP_EOL;

答案 3 :(得分:0)

self :: class === get_class()

static :: class === get_drawn_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());

会回来

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)