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

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

问题描述

所以我创建了这两个类

//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);
    }    
}

现在这是两者的非常简化的版本,但是足以说明我的问题.此处显示的类将无法使用,因为找不到四分之一类.为了使其正常工作,我可以将$ 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 = "\Resources\Quarter";

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

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 \Foo\Baz

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

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

$class = 'Foo\Baz';

(注意:无前导\.)

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

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

$class = __NAMESPACE__ . '\Baz';

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

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