Développement web indépendant à Montpellier

Publié le mercredi 27 mai 2009 09:35:05

Des espaces de noms en PHP

Les développeurs l'ont attendu longtemps, les namespaces existent désormais en PHP depuis la version 5.3.0, une avancée majeure pour tout ceux qui ont à inclure des librairies.

Qu'est-ce qu'un namespace ?

La définition large d'un namespace est un moyen d'encapsuler des choses : un exemple concret pris sur le site php.net : le fichier foo.txt peut exister dans le dossier /home/stephane et également dans /home/paul, mais 2 copies de ce fichier ne peuvent coexister dans le même dossier. De plus, pour accéder à foo.txt dans un autre dossier que celui qui le contient, il faut entrer son "adresse" absolue /home/stephane/foo.txt.

C'est le même principe dans le monde de la programmation.

En , les namespaces ont été implémentés pour résoudre 2 problèmes que les auteurs des librairies et applications rencontraient lorsqu'ils créaient des morceaux de code réutilisables :

  • Collision de nom : problème de nom de fonction/classes/constantes sur des parties tierces,
  • Augmenter la lisibilité du code, pour éviter les alias trop long.

Les namespaces sont donc un excellent moyen de grouper les classes PHP proches, les fonctions, les constantes pour rendre le code plus lisible et facilement ré-utilisable.

Déclarer un namespace

Pour déclarer un namespace dans un fichier PHP, il suffit d'ajouter en haut du fichier :

namespace MyProject;

Aucun code non PHP ne peut précéder la déclaration du namespace.

Déclarer un sous-namespace

Pour déclarer un sous-namespace :

namespace MyProject\Sub\Level;

Utilisation du caractère-clef "\", cela aurait été plus joli avec un point, mais c'est le fond qui compte !

Plusieurs namespace dans le même fichier

Contrairement à certains langages, il est possible de déclarer plusieurs namespace dans un seul fichier :

namespace MyProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
}

namespace { // global code
session_start();
$a = MyProject\connect();
echo MyProject\Connection::start();
}

Exemple d'utilisation du Namespace PHP

namespace my\name;

class MyClass {}
function myfunction() {}
const MYCONST = 1;

$a = new MyClass;
$c = new \my\name\MyClass; // utilisation du même nom de classe MyClass dans un autre namespace

$a = strlen('hi'); 
                
$d = namespace\MYCONST; 
$d = __NAMESPACE__ . '\MYCONST';
echo constant($d);

Le seul truc un peu regrettable, mais c'est habituel (malheureusement), c'est la syntaxe un peu moche ! (point de vue totalement subjectif)

Cet article et les exemples affichés sont tirés de la documentation officielle de PHP pas encore traduite à propos des namespace en PHP.

Notez cet article !

  • Actuellement 3 sur 5 étoiles
  • 1
  • 2
  • 3
  • 4
  • 5

Note : 3/5 (4 notes attribuées)

Merci d'avoir participé !

Vous avez déjà noté cette page, vous ne pouvez la noter qu'une fois !

Votre note a été changée, merci de votre participation !

Bonne résolution ! j'arrête d'alourdir mes pages avec des boutons de partage, mais vous pouvez continuer de partager :-)

Commentaires

  1. http://ww... | http://www.fitclick.com/www/cms/content/view/ViewEntryGroup.aspx?entryGroupID=73317#.W_r-MOgzY2w |

    Thank you for the interesting and exclusive comprehensive information :)
    Very good information. nice day!

  2. the more fundamental issue was the shortage of R&D and application of domestic chips

  3. Mostly we face problems while writing assignments is because of lack of writing skills or we don’t know from where I will get proper information for my assignment. To solve this issue many assignment help online service are available in market.

  4. Your work is very good and I appreciate you and hopping for some more informative posts. Thank you for sharing great information to us.
    http://...mandatory/

  5. Your work is very good and I appreciate you and hopping for some more informative posts. Thank you for sharing great information to us.
    http://...provement/

  6. This is a great post. I like this topic.This site has lots of advantage.I found many interesting things from this site. It helps me in many ways.Thanks for posting this again.

  7. Hi, I find reading this article a joy. It is extremely helpful and interesting and very much looking forward to reading more of your work.
    http://...dvisor.com

  8. Thank you for the interesting and exclusive comprehensive information :)

  9. It is a great website.. The Design looks very good.. Keep working like that!
    http://...g-methods/

  10. Thank you for some other informative website. The place else may just I get that kind of information written in such a perfect method? I have a venture that I am simply now running on, and I’ve been at the glance out for such info.
    http://...its-types/

  11. Kiaan Roy | Kiaan Roy |

    There's no need to deal with a shared print spooler crashing because the shared print spooler is eliminated along with the print server. Instead you get direct IP printing through Printer's one-to-one connections between client devices and printers.

    https:/...pport.html

    https:/...pport.html

  12. Kiaan Roy | Kiaan Roy |

    Well, first and foremost, Printer's enterprise print management solution allows your organization to eliminate print servers completely and replace them with one centralized server running a single instance of our next-generation software—or even replace them with our serverless SaaS solution, Printer Cloud.

    https:/...pport.html

    https:/...pport.html

  13. Kiaan Roy | Kiaan Roy |

    That's no way to run an enterprise print environment. In mixed 32-/64-bit scenarios, Printer gives you considerably more peace of mind because it allows these two very different architectures to work seamlessly alongside one another.
    https:/...pport.html

    https:/...pport.html

  14. Kiaan Roy | Kiaan Roy |

    To fix the print spooler, it then becomes necessary to identify the offending driver (which, as I noted, is tough because of the identical names), fully remove or disable it, and then restart the print spooler with your fingers crossed.


    https:/...pport.html

    https:/...pport.html

  15. Kiaan Roy | Kiaan Roy |

    Unfortunately, in some common configurations, the 32-/64-bit drivers have to have identical names. This has the potential to cause a great deal of confusion—and, of course, print spooler crashing should one of these drivers be deployed to or accessed by the wrong client.
    https:/...pport.html

    https:/...pport.html

  16. Kiaan Roy | Kiaan Roy |

    Many other admins have taken the "please play nice" approach and tried to maintain a mixed environment. This typically involves trying to operate 32- and 64-bit software side by side and hoping for the best.
    https:/...pport.html

    https:/...pport.html

  17. Your site is truly cool and this is an awesome motivating article. Much thanks to you to such an extent.http://...ontest.com

  18. I discovered your this post while hunting down some related data on website search...Its a decent post..keep posting and upgrade the data.
    http://...ooking.com

  19. wow this good but ,I like your post and good pics may be any peoples not like because defrent mind all poeple ,
    http://...wark.co.uk

  20. Your post was very nicely written. I’ll be back in the future for sure!
    http://...oncept.net

  21. I want to encourage that you continue your great writing, have a nice day!

  22. This service is a boon for the end users by providing support but is also a blessing to those who are looking for jobs. In the current market scenario it is tough to find the right job, therefore a service like this which provides an opportunity to the qualified and experienced people to earn money is a real winner.
    http://...ne-number/

  23. Not only that you also have the convenience of calling them anytime of the day or night meaning 24 hours and 7 days a week without being told that it is a weekend and they are off.
    http://...ne-number/

  24. You will not be put on hold endlessly while the answer is being searched on the other end. Having experts on the other end makes sure that they do not fumble or look up for the solution when the call is made.
    http://...ne-number/

  25. Having experts on the other end makes sure that they do not fumble or look up for the solution when the call is made.
    http://...ne-number/

  26. When looking for the online tech support phone number and finally making a call you are assured of quality and practical solutions based on your specific problem.
    http://...ne-number/

  27. Talking to a real person is not only refreshing but also easier as we can ask for instructions again and again till the time problem is sorted out.
    http://...ne-number/

  28. sdfdffffffffffffffffff

  29. Mausam Roy | Packers and Movers Thane |

    Movers and Packers industry is a big industry in. However, there are many packers and movers in and not all are reliable and efficient. Therefore, you should be prudent enough and must act wisely to choose the best packers and movers in the city More information:
    https:/...ers-thane/

  30. Mausam Roy | Packers and Movers Surat |

    Packers and movers is an ever-growing industry. More and more people are shifting to new places for better jobs, better lifestyle, better opportunities, etc. is the ‘Industrial capital of India’ and so many people shift to and from this city every day More information:
    https:/...ers-surat/

  31. Mausam Roy | Packers and Movers Ahmedabad |

    The Packers and Movers should be professional and not work in a lazy and inefficient manner. They should be well aware of the way packaging is done and ensure no damage or loss to property. Further, they should also be co-operative and friendly so that the customers have a pleasant experience of taking their services More information:
    https:/...ahmedabad/

  32. Mausam Roy | Packers and Movers Faridabad |

    The Movers And Packers should be able to provide timely services. They should start the work on time and complete it within the stipulated time. There should be no complaints about delay in work More information: https:/...faridabad/

  33. Mausam Roy | Packers and Movers Ghaziabad |

    Furniture needs careful packaging to avoid any sort of damage. Exercise types of equipment also need proper wrapping etc. so that it reaches safely. Your precious crockery is another item that can easily break if not properly packed More information:
    https:/...ghaziabad/

  34. Webroot.com/safe- Experience next-generation Security level with Webroot on your all devices. Install and activate webroot from www.webroot.com/safe and don’t forget to run webroot safe scan to feel secure anywhere.webroot.com/safe is a computer security software program for Microsoft Windows users that combine software as a service cloud protection with traditional Antivirus and anti-spyware desktop technologies. Built into the suite is a two-way firewall, a registry cleaner, Email anti-spam, secure browsing, anti-phishing and a password management service. The suite was initially released on July 26, 2010, as the 2011 version of the product.

    http://...t.com/safe

  35. Achieve3000 provides online differentiated instruction with the goal of improving reading comprehension in pre-k through 12th-grade students as well as adult learners.

    http://...ieve-3000/

  36. Great blog!
    Thanks for sharing

  37. Our Norton Setup Support team is always available to help client round the clock. We are a third party company who is well-known to provide help and guideline about PC virus and malware. We are providing solutions fast and perfectly for any issues. Our Norton Setup Support is recognized for its effective remote support by phone or Email. We Guide the Customers to complete some procedure to fix the query step by step. With the help of our Expert, solving the problems can just take several minutes. If still problems cannot solve, then we will remotely access your system and fix the problems. To get the telephone help, the user can call our number to talk with our specialist. People that are not able for telephone conversation can chat with one of the member of our Norton setup team. If you are not in hurry, then just drop an email to us. Our Response will be within few minutes.

  38. Norton Se... | Norton Setup with product key |

    If you have installed Norton Setup from norton.com/setup in your System, you will forever transfer from computer Threats, Viruses, and transfer that can harm or destroy the files that you kept on your system. Norton antivirus is a well-known Antivirus for its effective guarding capacity of data and files from any type of Threat attacks. Malware is generally produced with an aim to steal user's personal and sensitive information like credit card, password, IDs and bank account numbers and then apply them to rob or exchange these details to cyber criminal organizations. The malware may not visible but in actual, it is transferring the data to the owner who produced malware.

  39. I have no... | I have norton product key |

    Our Norton Setup Support team is always available to help client round the clock. We are a third party company who is well-known to provide help and guideline about PC virus and malware. We are providing solutions fast and perfectly for any issues. Our Norton Setup Support is recognized for its effective remote support by phone or Email. We Guide the Customers to complete some procedure to fix the query step by step. With the help of our Expert, solving the problems can just take several minutes. If still problems cannot solve, then we will remotely access your system and fix the problems. To get the telephone help, the user can call our number to talk with our specialist. People that are not able for telephone conversation can chat with one of the member of our Norton setup team. If you are not in hurry, then just drop an email to us. Our Response will be within few minutes.

  40. If you have installed Norton Setup from norton.com/setup in your System, you will forever transfer from computer Threats, Viruses, and transfer that can harm or destroy the files that you kept on your system. Norton antivirus is a well-known Antivirus for its effective guarding capacity of data and files from any type of Threat attacks. Malware is generally produced with an aim to steal user's personal and sensitive information like credit card, password, IDs and bank account numbers and then apply them to rob or exchange these details to cyber criminal organizations. The malware may not visible but in actual, it is transferring the data to the owner who produced malware.

  41. Our Norton Setup Support team is always available to help client round the clock. We are a third party company who is well-known to provide help and guideline about PC virus and malware. We are providing solutions fast and perfectly for any issues. Our Norton Setup Support is recognized for its effective remote support by phone or Email. We Guide the Customers to complete some procedure to fix the query step by step. With the help of our Expert, solving the problems can just take several minutes. If still problems cannot solve, then we will remotely access your system and fix the problems. To get the telephone help, the user can call our number to talk with our specialist. People that are not able for telephone conversation can chat with one of the member of our Norton setup team. If you are not in hurry, then just drop an email to us. Our Response will be within few minutes.

  42. www.webro... | www.webroot.com/safe | webroot/safe - download (windows 10) |

    www.webroot.com/safe -24/7 technical support for Webroot antivirus, call us to get instant support on webroot installation issues Dial toll free 1-844-833-0610.
    http://....org/safe/

  43. www.webro... | www.webroot.com/safe | Activate webroot at webroot safe |

    Where to seek out webroot Key Code? The Webroot security package is simple to setup & install at webroot.com/safe. Simply find 20-character alpha-numeric code that is...
    http://...-safe.org/

  44. Web-root -24/7 technical support for Webroot antivirus, call us to get instant support on webroot installation issues Dial toll free 1-844-833-0610.
    http://...b-root.org

  45. webroot.c... | webroot.com/safe to get webroot safe setup |

    Experience next generation Security level with Webroot in your all devices. Install and activate webroot from www.webroot.com/safe and don’t forget to run webroot safe scan to feel secure anywhere.webroot.com/safe is a computer security software program for Microsoft Windows users that combine software as a service cloud protection with traditional Antivirus and anti-spyware desktop technologies. Built into the suite is a two-way firewall, a registry cleaner, Email anti-spam, secure browsing, anti-phishing and a password management service .The suite was initially released on July 26, 2010 as the 2011 version of the product.
    http://...-com-safe/

  46. Visit www.norton.com/setup for setup, download, reinstall, enter and activate your norton product key to setup your account.Step-by-Step guide for Norton setup key, Download & installation from norton.com/setup website.

  47. welcome to avg.com/retail website With the development of the digital world, online protection is crucial. It is extremely important to protect your PCs, Mac, computers as well as mobile devices and tablets with avg.com/retail. This can be done with the help of effective internet security and anti-virus products from avg.com/retail that safeguards all devices used on digital platforms.

  48. check it right now for Madhya Pradesh Board of Secondary Education results mpbse.nic.in

  49. www.tnresults.nic.in As every year the Government of Tamil Nadu has conducted TN Board

  50. https:/...ro.online/ Modro is an application is an unlimited TV video streaming app for Android users

  51. It would appear that the author has put a considerable measure of diligent work into this.

  52. Hi, Your blog is truly faultless and unique.Very wonderful your article, This is best article. I read really perfect your article more information one of other blog zone. So I like it. thank so much for sharing this article to us

  53. Thanks
    <a href="http://...t;>will writing service groupon</a>

  54. Mirinda | Good post |

    <a href="https:/...ing/" title="will writing service groupon">will writing service groupon</a>

  55. Hora d`Ara | Comment |

    Thanks for your post
    <a href="http://...ding" title="will writing service groupon">will writing service groupon</a>

  56. Self confident and stunning in equivalent measures, an absolute necessity read.

  57. Hi buddy, your blog' s design is simple and clean and i like it. Your blog posts about Online Dissertation Help are superb. Please keep them coming. Greets!!

  58. nice post....<a href="https:/...;>teatv android</a>

  59. This is really a great stuff for sharing. Keep it up. Thanks for sharing.

  60. Really i appreciate the effort you made to share the knowledge. 

  61. how to ma... | how to make a girl squirt |

    Easily With G-Spot Stimulation

  62. happy new... | happy new year 2018 Quotes |

    Happy New Year 2018 Images is knocking on the door, and everyone is excited to celebrate with their loved ones

  63. vlc playe... | vlc player download for windows |

    VLC Player has successfully made their stand as the best media player in the app market over the past few years

  64. http://ww... | http://www.agenslutena.com/penyebab-retina-lepas-ablasio-retina-obat-ampuh-tanpa-operasi/ |
  65. On the off chance that it’s another Mac is ought to run OS X El Capitan, the most recent rendition of the Mac working framework


  66. www..hotmail.com Hello, friends, want to login into hotmail.com sign in are you excited to read this article

  67. Shazam is a cell phone application to recognize the music being played in the environment

  68. Garageband is one of the most popular apps that are known for its best music composing the application

  69. sf@gmail.com | http://www.icouponkart.com/functions-using-melanotan-2-skin-tanning-process/ |

    Been hunting down such a wonderful blog like this for quite a while.

  70. hhhh2019q... | http://www.icouponkart.com/functions-using-melanotan-2-skin-tanning-process/ |

    This blog did complete justice to topic’s essence.

  71. Tonsil stones are otherwise called tonsilloliths

  72. Tonsil stones most of the times aren’t even too acute to be realised, hence, at times the person who has them doesn’t has an idea about its existence

  73. You are so cool! I don't suppose I have read through anything like that before. So wonderful to find someone with some unique thoughts on this subject matter. Seriously.. many thanks for starting this up. This website is something that is needed on the internet, someone with a little originality! <a href="http://...ot;>Gta 5 hack</a>


  74. aptoide app Aptoide app is one of the best platforms that allow users to download a plethora of applications easily

  75. jgvbsd@gm... | Avens Online |

    Journal of Clinical & Medical Case Reports Journals is an online Open Access clinical database of the most important happenings in the fields of medicine & surgery. http://...rts/home-9

  76. gvdg@gmai... | Avens Online |

    Journal of Clinical & <a href="http://...gt;Medical Case Reports Journals</a> is an online Open Access clinical database of the most important happenings in the fields of medicine & surgery.

  77. Happy New year 2018: Status, Advance Wishes, Quotes Messages, New year 2018 Images, Hd Wallpapers, Gif, Whatsapp Status, Pictures

  78. Mobdro Download application has two renditions: Freemium and Premium. Freemium is totally free

  79. dg@gmail.com | search engine optimization agency |

    This blog is a first class work, It is indeed a classic work of art.

  80. Tonsil stones are accumulation of the bacterial debris on the crevices of the tonsils

  81. One of the major social medium hike about sharing photos and videos in their personal space

  82. Top 5 Best Body Groomer List for Men

  83. The blog is exceptionally splendid. Just love the way how all the writing has been put.

  84. Lucky Patcher app offers you an improved surfing experience at no cost

  85. appvndownload Appvn is the app that you wish that you had. It is the all new app store and lets you get the apps

  86. Early watches are very expensive, in addition to <a href="http://...gt;replica watches</a> timing, the main is used to show off the status of identity. To 1920, wearing a watch on the wrist has been popular, after a few decades, the Swiss watch industry has been the world's leading position. Many manufacturers are committed to <a href="http://...;>rolex replica watches</a> pocket watch, pocket table function combination, increase the calendar, automatic winding, timer and other functions, to be miniaturized, so that the popularity of watches.In 1970, the quartz technology began to <a href="http://...gt;replica watches uk</a> dominate the watch industry, but the Swiss company launched the antique table series swept the world, to the late 80s, the Swiss company began to produce a variety of luxury mechanical watches, this tendency followed by further development, strengthening, Or automatic mechanical watches are increasingly favored. Today, Switzerland has the vast majority of <a href="http://...t;replique montres</a> the world's top watch brands.

  87. Showbox is an android based entertainment app that offers the android used free access to the largest collection of free movies

  88. File Explorer the best option for viewing and managing the files on your Android device

  89. Mobdro are further making it exciting to view anything from around the world as per ease and choice

  90. Mobdro is an extraordinary spilling application for android telephones and tablets

  91. ibps cler... | ibps clerk answer key 2017 |

    ibps clerk answer key 2017 Here is the www.ibps.in Clerical Exam Cutoff Marks 2017 update. IBPS Clerk Prelims Exam Solution sheet 2017

  92. uc browse... | uc browser for windows 10 |

    UC Browser is created by UC Web-A versatile web organization

  93. Cogniflex is a recently propelled supplementation which cases to enhance memory, learning, center, consideration and other intellectual aptitudes of a man

  94. sf@gmail.com | free walking tour stockholm |

    Use of refined and mesmeric is all that is needed to produce such a magnificent blog.

  95. Be it an Android user or Apple, we all have a tendency to opt for some tricks and hacks for our favorite games and applications

  96. Download... | Download Facetime for PC |

    We have ten really good alternatives

  97. Offers, coupons, rebates, and arrangements. There will come a period when most online vendors will be confronted with the choice of whether to offer rebates

  98. Showbox is a stunning application intended to watch motion pictures and TV appears on your Android for nothing

  99. Mobdro for ios is a free online video streaming app which is used to watch popular Live TV shows and programs for free and also helps to watch latest movies

  100. A portal where you can search for any Indian Pvt Ltd Registered company. Private Limited companies are those whoch are registered under RoC Indian Company Finder

  101. Chromecast Ultra. Stream your favourite entertainment in up to 4K

  102. you can download recordings with a single tick by utilizing showbox

  103. Process of downloading applications from aptoide

  104. bluestack... | bluestacks download for windows 8 |

    Because of its popularity, most of the users want to operate the app on PC. bluestacks

  105. avast saf... | avast safezone browser |

    avast safezone browser Prptection for Windows 10

  106. 9Game official website provides download and guide for 9Apps

  107. anybody can make their own Android application store with Aptoide

  108. With this app in your phone, there is much more you can do with it than just talking. Think of carrying your entertainer idiot box in your pocket, think of VidMate

  109. Showbox f... | Showbox for PC Download |

    We always suggest, using the latest updated edition of the Show

  110. Safari Br... | Safari Browser for windows |

    At long last, there's one more trap to know in Safari

  111. Users need not perform any in-app purchase of coins if they use Kingroot

  112. There are several benefits of seeing movies online on apps like Showbox

  113. Download... | Download Lucky Patcher |

    Killer is one of the best applications for hacking in-app purchases from gaming apps

  114. 100% genuine and free online whatsapp hacker service. Now hack whatsapp in just 2 or 3 minutes with this whatsapp spy services for free, Join Facebook to connect with WhatsApp Hack and others you may know. if you are looking for a WhatsApp spy tool to investigate the truth about your partner or children, this post can surely help you out!

  115. keeping in mind the end goal to research reality, individuals are left with no decision other than to hack WhatsApp Hack

  116. Safari 5 for Windows presents Top Sites , or landing page, where exquisite view we can see the most regularly gone by our page

  117. Very useful post. This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. Really its great article. Keep it up!

  118. Make Goog... | Make Google my Homepage in Firefox |

    Select Google from the drop-down menu

  119. Your article is great and rewarding. I like it very much. Hope to read more posts from you.
    http://...views.com/

  120. If truth be told informative and valuable detail is here.

  121. Stephanie | Good Post |

    The question that you have asked is not that simple and it is also not even possible to give the answer it just in a few words or lines. I will suggest you to take some expert opinion in this regard and will recommend you to get in touch with some professors of online university.
    http://...xperience/

  122. KingRoot is easy to use application for rooting and is quite popular among its users

  123. kindle cu... | kindle customer service phone number |

    We provide the best service for <a href="http://...>kindle customer service phone number</a>, Paperwhite, Oasis & Voyage. Call us to get most suitable help & support for your Kindle.

  124. jessicaalex | Nice post |

    All things http://...ntuk.co.uk considered, nothing I can say except for incredible! I trust you will make more helpful articles in the up and coming days.