Benefits of Using PHP Names

After doing some research on the namespace in PHP, I am trying to figure out what are the real benefits other than having library elements grouped together and reusing the same class name.

What I don't like about namespaces is the extra lines at the top of the file that you call in classes from "use core \ whatever \ class", which you don't need for the standard approach.

Also - something that I could not find information about what happens in a situation where we need to use two classes with the same name, but in different folders that contain the same method name? We would still need to name the namespace, but how would the code determine which method to use from the class?

I just started with namespaces, so excuse me if this question seems very simple.

Also - how does this work with static methods - for example, like the Helper class - should I also indicate that I need this namespace 'use core \ whatever \ Helper'?

+5
source share
3 answers

If you have a large project with many classes, you will end up with naming conflicts. You have db/mysql/adapter.phpand http/curl/adapter.php. To deal with this without namespaces, you must give your classes unique names, such as Db_Mysql_Adapterand Http_Curl_Adapter, and whenever you access these classes, you need to use their full name.

Db\Mysql\Adapter Http\Curl\Adapter Adapter Mysql\Adapter Curl\Adapter . .

Zend Framework 1 2, .

, , , ? , , ?

Db\Mysql, Adapter::foo() Db\Mysql\Adapter, \Http\Curl\Adapter::foo() . , :

namespace Db\Mysql;
use Http\Curl\Adapter as HAdapter;

Adapter::foo();  // Mysql adapter
HAdapter::foo(); // Http adapter, same as:
\Http\Curl\Adapter::foo();
+12

, , , "use core\whatever\class", .

. PHP, , . , . (DRY), , !

, , , ? , , ?

, . , ? , , api.document.events api.ajax.events. .

+1

@deceze.

, . ?

1.) , . :

namespace Db\Mysql;
use Http\Curl\Adapter as HAdapter;

include('Db/Mysql/Adapter.php');
include('Http/Curl/Adapter.php');   

Adapter::foo();  // Mysql adapter
HAdapter::foo(); // Http adapter, same as:
\Http\Curl\Adapter::foo();

2.) adapter.php, :

<?php
// this is Db/Mysql/Adapter.php

namespace Db/Mysql;

class Adapter {
  static function foo() {
  }
}

?>

:

include('db/mysql/adapter.php');
include('http/curl/adapter.php');

MysqlAdapter::foo(); // Mysql adapter
CurlAdapter::foo(); // Http adapter

A adapter.php :

<?php
// this is Db/Mysql/Adapter.php

class MysqlAdapter {
  static function foo() {
  }
}

?>

, , . .

The only argument that may exist is that you avoid problems with conflicting third-party libraries . But how many name conflicts have you had in the past? And how many libraries do you know that use namespaces, so you don’t have to edit all the files?

The fact is that in the real world there is no use. This is something accepted from world C that adds more confusion than benefits, in my opinion.

0
source

All Articles