Tuesday, 16 October 2018

PHP Namespaces for WordPress – a No Nonsense Guide


PHP namespaces are almost ten years old. Yes, a decade has passed (and yes, you’re getting old). Despite a decade passing by since PHP v5.3 was released many developers still don’t have a basic understanding of namespaces. Truth be told WordPress doesn’t use namespaces so “you don’t need to know how to use namespaces if you only work with WordPress.” You don’t need to be a namespace ninja but getting a grasp on the basics is simple and does you good. When there’s no namespace support – use a prefix
For a long, long time PHP didn’t have native namespace support. That’s why WordPress and a lot of other big codebases don’t use native namespaces. They weren’t around when needed, so prefixes are used.
Namespacing is important because it makes sure your function write_to_log() hasn’t already been defined by another piece of code. To avoid name clashing everything in global scope needs a prefix so the function becomes awesome_project_write_to_log() and all other functions and variables get the awesome_project_ prefix too. Simple? It is! Pretty? Not exactly.
There are some alternatives to that approach like
Source: https://managewp.org/articles/17978/php-namespaces-for-wordpress-a-no-nonsense-guide



source https://williechiu40.wordpress.com/2018/10/16/php-namespaces-for-wordpress-a-no-nonsense-guide/

No comments:

Post a Comment