使用 ::class 动态获取类名

huangapple go评论66阅读模式
英文:

Using ::class dynamically

问题

I want to create a helper method for my app where I pass a class name as a string. The method should then resolve the string into a fully qualified class name. So with namespace.

This is what I want to do. However, my IDE (PHPStorm) says: "is only allowed on objects"

public function(string $className)
{
    return $className::class;
}

Question: What do I have to change to make this dynamic?

英文:

I want to create a helper method for my app where I pass a class name as a string. The method should then resolve the string into a fully qualified class name. So with namespace.

This is what I want to do. However, my IDE (PHPStorm) says: "is only allowed on objects"

public function(string $className)
{
    return $className::class;
}

Question: What do I have to change to make this dynamic?

答案1

得分: 3

如果类始终位于特定命名空间中,您可以将其硬编码,并检查类是否存在。您可以根据需要处理错误,这只是抛出异常。

将类放在特定命名空间中还可以限制其使用的可能类,并且还可以帮助开发人员查看这些类的定义位置。

public function className(string $className)
{
    $fullName = '\YourNameSpace\\' . $className;
    if (class_exists($fullName) === false) {
        throw new Exception('Class not found');
    }

    return $fullName;
}
英文:

If the class is always in a specific namespace, then you can hard code it and also check if the class exists. You can handle the error as you need to, this just throws an exception.

Having the classes in a specific namespace also allows you to limit the possible classes it uses and it also can help developers as they can see where these classes are defined.

public function className(string $className)
{
    $fullName = '\YourNameSpace\\' . $className;
    if (class_exists($fullName) === false) {
        throw new Exception('Class not found');
    }

    return $fullName;
}

huangapple
  • 本文由 发表于 2023年5月24日 22:57:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76324880.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定