Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

So I created these two classes

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
282 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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

$class = 'FooBaz';

(Note: no leading .)

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

$class = __NAMESPACE__ . 'Baz';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...