开发者

PHP Class Namespaces vs Prefixes

开发者 https://www.devze.com 2023-03-09 12:34 出处:网络
Just a quick question on your preference of using PHP namespaces or class prefixing. <?php // ----- namespace -----

Just a quick question on your preference of using PHP namespaces or class prefixing.

<?php
// ----- namespace -----
开发者_StackOverflowuse My\Namespace;
$object = new Namespace\Object;

// ----- prefix with PR -----
$object = new PF_Object; //or
$object = new PFObject;

Which do developers prefer? I know why the use of namespaces can bring great advantage to applications, but also can quite a hindrance in PHP in my own opinion.

Thanks!


Combine use with an alias:

use My\Namespace\Foo as Foo;

$object = new Foo;

It's also useful like so:

namespace My\Debug\Stuff;
use My\Production\Stuff\Foo as BaseFoo;

class Foo extends BaseFoo {}


Why would you consider namespaces a hindrance?

class prefixing seemed to me like a sort of a hack to implement 'in code' a mecanism to implement namespaces.

Newer code now has the option to use a native built-in way of handling namespaces. This is a much cleaner approach, in my very humble opinion.

Consider this popular yet eye-opening example that allows legacy code to use namespace:

// Using native namespace features to shorten class prefixes

<?php
use Sabre_DAV_Auth_Backend_PDO as AuthBackend;
use Zend_Controller_Action_Helper_AutoComplete_Abstract as AutoComplete;

$backend = new AuthBackend();
?>


Clearly, there's no need to use the underscore character to fake namespaces any more, so I suppose the question boils down to "is it a good idea to use underscore characters in class names".

IMO, the answer is no, firstly because it looks ugly (IMO) and secondly because some older class loaders could get confused by a class name that includes an underscore.


well if you are running PHP 5.2.X you only have the option 2

but if you are running PHP 5.3.Xyou could use both.

In my case running PHP 5.3.X I would use the feature that the new version of the language offers. To make an analogy is likely be running JAVA 1.6 and don't use generics (or sort of)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号