Php class name and function name same

Php class name and function name same

Что такое пространства имён? В широком смысле — это один из способов инкапсуляции элементов. Такое абстрактное понятие можно увидеть во многих местах. Например, в любой операционной системе директории служат для группировки связанных файлов и выступают в качестве пространства имён для находящихся в них файлов. В качестве конкретного примера файл foo.txt может находиться сразу в обеих директориях: /home/greg и /home/other , но две копии foo.txt не могут существовать в одной директории. Кроме того, для доступа к foo.txt извне директории /home/greg , мы должны добавить имя директории перед именем файла используя разделитель, чтобы получить /home/greg/foo.txt . Этот же принцип распространяется и на пространства имён в программировании.

В PHP пространства имён используются для решения двух проблем, с которыми сталкиваются авторы библиотек и приложений при создании повторно используемых элементов кода, таких как классы и функции:

  1. Конфликт имён между вашим кодом и внутренними классами/функциями/константами PHP или сторонними.
  2. Возможность создавать псевдонимы (или сокращения) для Ну_Очень_Длинных_Имён, чтобы облегчить первую проблему и улучшить читаемость исходного кода.

Пространства имён в PHP предоставляют возможность группировать логически связанные классы, интерфейсы, функции и константы.

Пример #1 Пример синтаксиса, использующего пространство имён

namespace my \ name ; // смотрите раздел «Определение пространств имён»
class MyClass <>
function myfunction () <>
const MYCONST = 1 ;

$a = new MyClass ;
$c = new \ my \ name \ MyClass ; // смотрите раздел «Глобальная область видимости»

$a = strlen ( ‘hi’ ); // смотрите раздел «Использование пространств имён: возврат
// к глобальной функции/константе»

$d = namespace\ MYCONST ; // смотрите раздел «оператор пространства имён и
// константа __NAMESPACE__»
$d = __NAMESPACE__ . ‘\MYCONST’ ;
echo constant ( $d ); // смотрите раздел «Пространства имён и динамические особенности языка»
?>

Замечание: Имена пространств имён регистронезависимы.

Замечание:

Пространства имён PHP или составные имена, начинающиеся с этого слова (например, такие как PHP\Classes ), зарезервированы для нужд языка, их не следует использовать в пользовательском коде.

User Contributed Notes 7 notes

Thought this might help other newbies like me.

Читайте также:  Java enterprise edition oracle

Name collisions means:
you create a function named db_connect, and somebody elses code that you use in your file (i.e. an include) has the same function with the same name.

To get around that problem, you rename your function SteveWa_db_connect which makes your code longer and harder to read.

Now you can use namespaces to keep your function name separate from anyone else’s function name, and you won’t have to make extra_long_named functions to get around the name collision problem.

So a namespace is like a pointer to a file path where you can find the source of the function you are working with

Just a note: namespace (even nested or sub-namespace) cannot be just a number, it must start with a letter.
For example, lets say you want to use namespace for versioning of your packages or versioning of your API:

namespace Mynamespace\1; // Illegal
Instead use this:
namespace Mynamespace\v1; // OK

To people coming here by searching about namespaces, know that a consortium has studied about best practices in PHP, in order to allow developers to have common coding standards.

These best practices are called «PHP Standard Recommendations» , also known as PSR.

They are visible on this link : http://www.php-fig.org/psr

Actually there are 5 coding standards categories :
PSR-0 : Autoloading Standard , which goal is to make the use of Namespaces easier, in order to convert a namespace into a file path.
PSR-1 : Basic Coding Standard , basically, standards 🙂
PSR-2 : Coding Style Guide, where to put braces, how to write a class, etc.
PSR-3 : Logger Interface , how to write a standard logger
PSR-4 : Improved Autoloading , to resolve more Namespaces into paths.

Читайте также:  Массив java заполнить целыми числами

The ones I want to point are PSR-0 and PSR-4 : they use namespaces to resolve a FQCN (Fully qualified class name = full namespace + class name) into a file path.
Basic example, you have this directory structure :
./src/Pierstoval/Tools/MyTool.php

The namespacing PSR-0 or PSR-4 standard tells that you can transform this path into a FQCN.
Read the principles of autoload if you need to know what it means, because it’s almost mandatory 😉 .

// /index.php
include ‘autoloader.php’ ;
$tool = new Pierstoval / Tools / MyTool ();
?>

// /src/Pierstoval/Tools/MyTool.php
namespace Pierstoval \ Tools ;
class MyTool <>
?>

// /autoloader.php
function loadClass ( $className ) $fileName = » ;
$namespace = » ;

// Sets the include path as the «src» directory
$includePath = dirname ( __FILE__ ). DIRECTORY_SEPARATOR . ‘src’ ;

if ( false !== ( $lastNsPos = strripos ( $className , ‘\\’ ))) $namespace = substr ( $className , 0 , $lastNsPos );
$className = substr ( $className , $lastNsPos + 1 );
$fileName = str_replace ( ‘\\’ , DIRECTORY_SEPARATOR , $namespace ) . DIRECTORY_SEPARATOR ;
>
$fileName .= str_replace ( ‘_’ , DIRECTORY_SEPARATOR , $className ) . ‘.php’ ;
$fullFileName = $includePath . DIRECTORY_SEPARATOR . $fileName ;

if ( file_exists ( $fullFileName )) require $fullFileName ;
> else echo ‘Class «‘ . $className . ‘» does not exist.’ ;
>
>
spl_autoload_register ( ‘loadClass’ ); // Registers the autoloader
?>

A standardized autoloader will get the class you want to instanciate (MyTool) and get the FQCN, transform it into a file path, and check if the file exists. If it does, it will it, and if you wrote your class correctly, the class will be available within its correct namespace.
Then, if you have the following code :

The autoloader will transform the FQCN into this path :
/src/Pierstoval/Tools/MyTool.php

This might be the best practices ever in PHP framework developments, such as Symfony or others.

Читайте также:  Matplotlib python ширина графика

Источник

Оцените статью