Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To PHP Namespace or not to PHP Namespace [closed]

Tags:

namespaces

php

ok, I'm relatively new to PHP programming and have been plodding along quite unaware that it is possible to actually use namespaces in PHP as I can in c# etc.

It's really ugly though as they have decided to use backslashes - why!?

Anyway, I am interested in other PHP programmers' views on whether namespaces will catch on in PHP and whether I should begin to use them now?

like image 602
David Avatar asked Jun 14 '10 22:06

David


People also ask

Should I use namespace PHP?

The main objective of namespaces is to prevent name collisions, more over they are used to group classes, methods. As you mentioned there are a lot of classes within a Laravel project so namespaces would have to be used to prevent collisions which will happen in big projects.

How does PHP namespace work?

Like C++, PHP Namespaces are the way of encapsulating items so that same names can be reused without name conflicts. It can be seen as an abstract concept in many places. It allows redeclaring the same functions/classes/interfaces/constant functions in the separate namespace without getting the fatal error.

What is true about namespace in PHP?

In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions: Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.

What is the difference between namespace and use in PHP?

A namespace is a way of grouping identifiers so that they don't clash. Using a class implies that you can create an instance of that class, not true with namespaces. 2. You can use using-declarations with namespaces, and that's not possible with classes unless you derive from them.


2 Answers

Here are some solution attempts for those wondering about name space functionality, without php 5.3.

First, I must say, only prefixing worked for me, the other solutions below are sort of notes not to go that way.

Namespace functionality can be needed if, for example, one produces wordpress plugins, using your valued function library in them. Normally you cannot have multiple plugins with function declarations of same functions, it would cause fatal errors.

SOLUTION 1: prefix all your library functions with plugin_name_ or namespace_

 function str_len_utf8($str) 

becomes

 function photoplugin_str_len_utf8($str) 

Is just a matter of find-replace. Easy if the functions are already prefixed uniquely:

john_str_len_utf8() => photoplugin_john_str_len_utf8() 

Good for the soul as well, supports the ego, 'johns string library' :D

If you choose short and nice prefixes with some common sense, it works like a charm, as they say.

SOLUTION 2: enclose all your library/reeuse functions in a class.

class photopluginlib      {      function str_len_utf8($a){ $a=$this->str_clean_utf8($a); ...}      ...      } 

All function calls in the class to the class are prefixed with $this->. Once this class is prepared, one can use it repeatedly without search-replace, changing the classname is enough. Usage:

$photopluginlib=new photopluginlibrary(); $b=$photopluginlib->str_len_utf8($a); 

SOLUTION 3: enclose all your library/reeuse functions in a class, and use :: operator

class photopluginlib      {      static function str_len_utf8($a){ $a=self::str_clean_utf8($a); ...}      ...      } 

All function declarations in the class have keyword static in front of function.

All function calls inside the class to the class are prefixed with self::

Once this class is prepared, one can use it without search-replace. The class name is the namespace, sort of. One only changes the class name and uses it as such.

$b=photopluginlib::str_len_utf8($a); $c=photopluginlib::database_row(...) 

No need to instantiate the class.

Looks nicer than $photopluginlib->str_len_utf8(), but I still prefer photoplugin_john_str_len_utf8()

Notes

  • all libraries need to go into 1 big library class declaration, you practically cannot add methods to classes later in php.
  • you cannot just declare new library functions here and there in different php files.
  • if multiple libraries are used, and they are using each other, they need to use self:: for function calls.
  • php5.2.17, common 2013, does not accept call_user_func('photopluginlib::functionname'), need to use call_user_func(Array('photopluginlib','functionname')) or inside class, call_user_func(Array(__CLASS__,'functionname')), which means code rewrite for wp add_action, preg_replace_callback etc.
  • needs php>=5
  • cannot mix code and function declarations, as in:

class photopluginlib{ add_filter('html','myfilter'); static function myfilter($html){return ''} }

  • For big code, it can quickly become a big complicated mind bender.

I prefer to just use prefixing until the real thing, namespaces, are widely available.

These solutions still mean one has to prefix all function uses. Namespace functionality would mean one can use functions without prefixing them, the prefix would be just once, at begin of the php file:

<?php namespace photoplugin; ... $b=str_len_utf8($a); 

By the way, upgrading to php5.3 has an additional advantage, if you can choose not to code for php5.2 (still everywhere, year 2013) Php5.3 vs php 5.2.17 means instant speed increase. It looks like %30 etc speed increases are available, not considering the database side:

http://onlinephpfunctions.com/benchmarks

Hope this helps inspire some solutions to those reaching for namespaces.

like image 166
Johan Avatar answered Oct 05 '22 09:10

Johan


Its use is already catching on. A couple of projects use it in their upcoming/beta versions. Most examples I've seen however use it like a cargo cult. Doctrine2 for example uses five or more nested namespaces (code smell), probably to provide a 1:1 mapping of namespace/class to the filesystem/directories. I guess the novelty makes PHP namespaces prone to unreasoned overuse.

Anyway, the syntax doesn't help with readability that much. And it's a big turn off for professional programmers. But if there is a serious use case in your project, just go for it. (Hypothetical naming conflicts are not the best reason.)

like image 30
mario Avatar answered Oct 05 '22 11:10

mario