【问题标题】:PHP: Is it possible to get the name of the class using the trait from within a trait static method?PHP:是否可以从特征静态方法中使用特征获取类的名称?
【发布时间】:2018-05-18 08:56:20
【问题描述】:

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

例如:

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

class SomeThing {
    use SomeAbility;
    ...
}

获取类名:

$class_name = SomeThing::theClass();

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

【问题讨论】:

    标签: php traits


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      是的,使用get_called_class()

      <?php
      trait SomeAbility {
          public static function theClass(){
              return get_called_class();
          }
      }
      
      class SomeThing {
          use SomeAbility;
      }
      // Prints "SomeThing"
      echo SomeThing::theClass();
      

      【讨论】:

        【解决方案3】:

        可以不带参数调用get_class()获取当前类的名字...

        trait SomeAbility {
            public static function theClass(){
                return get_class();
            }
        }
        
        class SomeThing {
            use SomeAbility;
        }
        
        echo SomeThing::theClass().PHP_EOL;
        

        【讨论】:

        • 这有一个问题——如果使用 trait 的类被扩展到另一个类,它将返回扩展该类的类的名称。
        【解决方案4】:

        self::class=== get_class()

        静态::class=== get_call_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)
        

        【讨论】:

        • 如果类通过扩展继承到另一个类,这些似乎都不起作用。
        猜你喜欢
        • 2019-06-30
        • 1970-01-01
        • 2017-06-03
        • 1970-01-01
        • 2021-10-28
        • 2018-06-08
        • 1970-01-01
        • 1970-01-01
        • 2016-05-27
        相关资源
        最近更新 更多