>namespace
> php 7中的名稱空間使用
<code class="php"><?php namespace MyProject\Utilities; class Helper { public function greet($name) { return "Hello, " . $name . "!"; } } ?></code>
Helper
此代碼在MyProjectUtilities
命名空間內定義了類use
。 要在另一個文件中使用此類,您必須使用完全合格的名稱或使用
<code class="php"><?php //Using fully qualified name echo MyProject\Utilities\Helper::greet("World"); ?></code>
use
>另外,您可以使用a語句來導入類:
<code class="php"><?php use MyProject\Utilities\Helper; echo Helper::greet("World"); ?></code>
>use
>Helper
> this use
語句導入use
類,允許您使用較短的名稱。您還可以使用{}
語句導入特定功能或常數。 如果您需要從同一名稱空間導入多個類或元素,則可以在php文件的頂部定義
<code class="php"><?php use MyProject\Utilities\{Helper, AnotherClass, MyConstant}; echo Helper::greet("World"); echo AnotherClass::someMethod(); echo MyConstant; ?></code>>語句:
<?php
declare
User
>類,但是在不同的名稱空間(例如User
>和LibraryAUser
)中,可以解決歧義。 LibraryBUser
comexamplemyproject
策略性地計劃您的名稱空間。 使用一致且描述性的命名約定,避免意外碰撞。 一種常見的做法是在項目域名上的基礎名稱逆轉(例如,
User
>的類,則應使用MyProjectUser
>和AnotherProjectUser
>清楚地指定您需要的一個類別。 use
use
<code class="php"><?php namespace MyProject\Utilities; class Helper { public function greet($name) { return "Hello, " . $name . "!"; } } ?></code>>
>
>>>如果您經常使用長期使用的類別使用一個完全合格的名稱,則可以使用以上是如何在PHP 7中使用名稱空間?的詳細內容。更多資訊請關注PHP中文網其他相關文章!