Name is a name that belongs to a certain class. Space is the space certain class is in. For example, you have two drawers, one's yours and another one your brother's. Now you both put your stuff in there, your watch, mobiles, pens storage devices etc.. One way to know which drawer belongs to who is to memorize its position, you could say my stuff is in the top drawers and your brother's in the bottom one.
Another and better way is to label them, you put your name on the first one, your brother puts his on his. That's essentially what namespace is in programming. You label your classes.
Have a look at this structure.
classes/html_parser_class.php
classes/captch_class.php
classes/validator_class.php
classes/login_parser_class.php
classes/jp_graph_class.php
You are working on a project that requires following classes, now imagine for a moment that "html_parser_class.php" has a class named "ShowTheData" but so does "jp_graph_class.php". What happens if we instantiate both of the class? A fatal error will display saying cannot redeclare (classname) in file you are trying to instantiate it in. All this hassle because both classs have same class name.
Imaging you are working on a class of your own and want to name it "ShowTheData", well unfortunately you can not, PHP will get confused and tell you that you cannot redeclare the class, even though your new class displays something completely differently than other two classes.
To solve this problem we label our classes. We go to our class file and user "namespace" keyword, with a label name. Like so:
namespace admin_login;
We go to every class file and label it. Now when we want to instantiate it we use, new keyword, our label name, backslash and the classname, like this:
$admin = new admin_login\Admin;
If you do this with every class you write, give it a label you can have same name
for different class without any issue.
No comments:
Post a Comment