将命名空间与从变量创建的类一起使用 [英] Using namespaces with classes created from a variable

查看:14
本文介绍了将命名空间与从变量创建的类一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我创建了这两个类

//Quarter.php
namespace Resources;
class Quarter {
    ...
}


//Epoch.php
namespace Resources;
class Epoch {

    public static function initFromType($value, $type) {
        $class = "Quarter";
        return new $class($value, $type);
    }    
}

现在这是两者的一个非常简化的版本,但足以说明我的问题.此处显示的类将不起作用,因为它找不到 Quarter 类.为了使它工作,我可以将 $class 变量更改为

Now this is a a very simplified version of both, but is enough to illustrate my question. The classes as they are shown here will not work as it will not find the Quarter class. To make it work I could change the $class variable to

$class = "ResourcesQuarter";

所以我的问题是:当两个类已经是同一个命名空间的成员时,为什么我需要在这里使用命名空间.仅当我将类名放入变量中时才需要命名空间:

So my question is: Why do I need to use the namespace here when both classes are already members of the same namespace. The namespace is only needed when I put the classname in a variable so doing:

    public static function initFromType($value, $type) {
        return new Quarter($value, $type);
    }    

将毫无问题地工作.为什么会这样?这里有什么我需要避免的潜在陷阱吗?

will work without problems. Why is this and is there any potential traps here I need to avoid?

推荐答案

因为字符串可以从一个命名空间传递到另一个命名空间.这使得名称解析充其量是模棱两可的,并且很容易引入奇怪的问题.

Because strings can be passed around from one namespace to another. That makes name resolution ambiguous at best and easily introduces weird problems.

namespace Foo;

$class = 'Baz';

namespace Bar;

new $class;  // what class will be instantiated?

某个命名空间中的文字没有这个问题:

A literal in a certain namespace does not have this problem:

namespace Foo;

new Baz;     // can't be moved, it's unequivocally FooBaz

因此,所有字符串类名"都是绝对的,需要写成FQN:

Therefore, all "string class names" are always absolute and need to be written as FQN:

$class = 'FooBaz';

(注意:没有前导.)

您可以将其用作简写,相当于类中的自引用 self:

You can use this as shorthand, sort of equivalent to a self-referential self in classes:

$class = __NAMESPACE__ . 'Baz';

这篇关于将命名空间与从变量创建的类一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆