Differences between traits and namespace for loading

6

Using namespace loads the file when a method is used say , if it does not invoke any of the class the file will not be loaded.

use World;
class Hello {
    World::say()
}

Using trait even without invoking method or property, the file is loaded at the time of use .

class Hello {
    use world;
}

I'm "starting" in traits , my question is about this behavior so different from namespace . Why do the USE does not load the namespace?

Is this a trait characteristic, or is there a setting that can only set traits when something is invoked?

    
asked by anonymous 14.09.2014 / 08:02

1 answer

6

Namespaces are used to group, encapsulate functionalities. It is basically used to avoid name conflict. It works like a last name for your members, so you can have two João s in your application since one is Silva and the other Oliveira .

In this case, use is used to indicate only that this family is available for use, ie all its members are accessible. But the limbs load will occur only on demand, after all the family is available to be called, but if you do not need a limb, you do not have to be physically present. It serves more as an indicative for the interpreter to know that the members of a namespace can be used.

Trait exists to allow reuse of code in classes that allow only simple inheritance. It is a way to add predefined behavior to a class.

In this case use has a completely different purpose, it indicates to the class that it must include among its members all the members of the specified trait . Trait is an integral part of the class, without it the class would not be complete, the content of trait is critical for the class to function, not optional. Even if an instance does not call any trait member it needs to be in the class to complete it, you can not have "limp" classes.

These two features share essentially the same syntax for the inclusion of external code but have completely different semantics and are conceptually distant. There is no relation between its use other than the fact that, by chance, a trait can be a member of a namespace .     

14.09.2014 / 13:29