The keyword "use" has been recycled for three distinct applications:
1- to import/alias classes, traits, constants, etc. in namespaces,
2- to insert traits in classes,
3- to inherit variables in closures.
This page is only about the first application: importing/aliasing. Traits can be inserted in classes, but this is different from importing a trait in a namespace, which cannot be done in a block scope, as pointed out in example 5. This can be confusing, especially since all searches for the keyword "use" are directed to the documentation here on importing/aliasing.Алијаси и увоз
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
Алијаси и увоз
Референца за `language.namespaces.importing.php` со подобрена типографија и навигација.
Користење на именски простори: Алијаси/Увоз
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
Користење на именски простори: Алијаси/Увоз
Способноста да се повика надворешно целосно квалификувано име со алијас, или увоз, е важна карактеристика на именските простори. Ова е слично на способноста на уникс-базирани датотечни системи да креираат симболични врски до датотека или до директориум.
PHP може да прави алијаси(/увезува) константи, функции, класи, интерфејси, траити, енами и именски простори. use Алијасирањето се постигнува со
оператор. Еве пример кој ги покажува сите 5 видови на увоз:
<?php
namespace foo;
use My\Full\Classname as Another;
// this is the same as use My\Full\NSname as NSname
use My\Full\NSname;
// importing a global class
use ArrayObject;
// importing a function
use function My\Full\functionName;
// aliasing a function
use function My\Full\functionName as func;
// importing a constant
use const My\Full\CONSTANT;
$obj = new namespace\Another; // instantiates object of class foo\Another
$obj = new Another; // instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
$a = new ArrayObject(array(1)); // instantiates object of class ArrayObject
// without the "use ArrayObject" we would instantiate an object of class foo\ArrayObject
func(); // calls function My\Full\functionName
echo CONSTANT; // echoes the value of My\Full\CONSTANT
?>Foo\Bar Имајте предвид дека за имињата во именски простор (целосно квалификувани имиња на именски простор што содржат разделувач на именски простор, како што е FooBarза разлика од глобалните имиња што не ги содржат, како што е
), водечката коса црта е непотребна и не се препорачува, бидејќи имињата за увоз мора да бидат целосно квалификувани и не се обработуваат релативно на тековниот именски простор.
PHP дополнително поддржува погодна кратенка за поставување повеќе изјави за употреба на ист ред
<?php
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
?>Пример #2 увоз/алијасирање со операторот use, повеќе изјави за употреба комбинирани
Увозот се изведува во време на компајлирање и затоа не влијае на динамичките имиња на класи, функции или константи.
<?php
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // instantiates object of class My\Full\Classname
$a = 'Another';
$obj = new $a; // instantiates object of class Another
?>Пример #3 Увоз и динамички имиња
Дополнително, увозот влијае само на неквалификувани и квалификувани имиња. Целосно квалификуваните имиња се апсолутни и не се погодени од увозот.
<?php
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // instantiates object of class My\Full\Classname
$obj = new \Another; // instantiates object of class Another
$obj = new Another\thing; // instantiates object of class My\Full\Classname\thing
$obj = new \Another\thing; // instantiates object of class Another\thing
?>Пример #4 Увоз и целосно квалификувани имиња
На use Правила за опсег за увоз use
клучниот збор мора да биде деклариран во најоддалечениот опсег на датотека (глобалниот опсег) или внатре во декларациите на именски простор. Ова е затоа што увозот се врши во време на компајлирање, а не во време на извршување, така што не може да биде во опсег на блок. Следниот пример ќе покаже незаконска употреба на
клучниот збор:
<?php
namespace Languages;
function toGreenlandic()
{
use Languages\Danish;
// ...
}
?>Забелешка:
Пример #5 Правило за незаконски увоз NOT наследи ги правилата за увоз на родителската датотека.
Група use declarations
Класите, функциите и константите што се увезуваат од истото namespace може да се групираат заедно во еден use
statement.
<?php
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;
use function some\namespace\fn_a;
use function some\namespace\fn_b;
use function some\namespace\fn_c;
use const some\namespace\ConstA;
use const some\namespace\ConstB;
use const some\namespace\ConstC;
// is equivalent to the following groupped use declaration
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};Белешки од корисници 16 белешки
The <?php use ?> statement does not load the class file. You have to do this with the <?php require ?> statement or by using an autoload function.Here is a handy way of importing classes, functions and conts using a single use keyword:
<?php
use Mizo\Web\ {
Php\WebSite,
Php\KeyWord,
Php\UnicodePrint,
JS\JavaScript,
function JS\printTotal,
function JS\printList,
const JS\BUAIKUM,
const JS\MAUTAM
};
?>Note that you can not alias global namespace:
use \ as test;
echo test\strlen('');
won't work.I couldn't find answer to this question so I tested myself.
I think it's worth noting:
<?php
use ExistingNamespace\NonExsistingClass;
use ExistingNamespace\NonExsistingClass as whatever;
use NonExistingNamespace\NonExsistingClass;
use NonExistingNamespace\NonExsistingClass as whatever;
?>
None of above will actually cause errors unless you actually try to use class you tried to import.
<?php
// And this code will issue standard PHP error for non existing class.
use ExistingNamespace\NonExsistingClass as whatever;
$whatever = new whatever();
?>Note the code `use ns1\c1` may refer to importing class `c1` from namespace `ns1` as well as importing whole namespace `ns1\c1` or even import both of them in one line. Example:
<?php
namespace ns1;
class c1{}
namespace ns1\c1;
class c11{}
namespace main;
use ns1\c1;
$c1 = new c1();
$c11 = new c1\c11();
var_dump($c1); // object(ns1\c1)#1 (0) { }
var_dump($c11); // object(ns1\c1\c11)#2 (0) { }If you are testing your code at the CLI, note that namespace aliases do not work!
(Before I go on, all the backslashes in this example are changed to percent signs because I cannot get sensible results to display in the posting preview otherwise. Please mentally translate all percent signs henceforth as backslashes.)
Suppose you have a class you want to test in myclass.php:
<?php
namespace my%space;
class myclass {
// ...
}
?>
and you then go into the CLI to test it. You would like to think that this would work, as you type it line by line:
require 'myclass.php';
use my%space%myclass; // should set 'myclass' as alias for 'my%space%myclass'
$x = new myclass; // FATAL ERROR
I believe that this is because aliases are only resolved at compile time, whereas the CLI simply evaluates statements; so use statements are ineffective in the CLI.
If you put your test code into test.php:
<?php
require 'myclass.php';
use my%space%myclass;
$x = new myclass;
//...
?>
it will work fine.
I hope this reduces the number of prematurely bald people.You are allowed to "use" the same resource multiple times as long as it is imported under a different alias at each invocation.
For example:
<?php
use Lend;
use Lend\l1;
use Lend\l1 as l3;
use Lend\l2;
use Lend\l1\Keller;
use Lend\l1\Keller as Stellar;
use Lend\l1\Keller as Zellar;
use Lend\l2\Keller as Dellar;
...
?>
In the above example, "Keller", "Stellar", and "Zellar" are all references to "\Lend\l1\Keller", as are "Lend\l1\Keller", "l1\Keller", and "l3\Keller".Something that is not immediately obvious, particular with PHP 5.3, is that namespace resolutions within an import are not resolved recursively. i.e.: if you alias an import and then use that alias in another import then this latter import will not be fully resolved with the former import.
For example:
use \Controllers as C;
use C\First;
use C\Last;
Both the First and Last namespaces are NOT resolved as \Controllers\First or \Controllers\Last as one might intend.Note that "use" importing/aliasing only applies to the current namespace block.
<?php
namespace SuperCoolLibrary
{
class Meta
{
static public function getVersion()
{
return '2.7.1';
}
}
}
namespace
{
use SuperCoolLibrary\Meta;
echo Meta::getVersion();//outputs 2.7.1
}
namespace
{
echo Meta::getVersion();//fatal error
}
?>
To get the expected behavior, you'd use:
class_alias('SuperCoolLibrary\Meta','Meta');Because imports happen at compile time, there's no polymorphism potential by embedding the use keyword in a conditonal.
e.g.:
<?php
if ($objType == 'canine') {
use Animal\Canine as Beast;
}
if ($objType == 'bovine') {
use Animal\Bovine as Beast;
}
$oBeast = new Beast;
$oBeast->feed();
?>In Chinese,there is an error in translation:
// 如果不使用 "use \ArrayObject" ,则实例化一个 foo\ArrayObject 对象
it should be
// 如果不使用 "use ArrayObject" ,则实例化一个 foo\ArrayObject 对象
/*********************************************/
中文下翻译有错误
// 如果不使用 "use \ArrayObject" ,则实例化一个 foo\ArrayObject 对象
这句话应该是
// 如果不使用 "use ArrayObject" ,则实例化一个 foo\ArrayObject 对象To clarify the distinction between inserting a trait in a class and importing a trait in a namespace, here is an example where we first import and then insert a trait.
<?php
namespace ns1;
trait T {
static $a = "In T";
}
namespace ns2;
use ns1\T; // Importing the name of trait ns1\T in the namespace ns2
class C {
use T; // Inserting trait T in the class C, making use of the imported name.
}
namespace main;
use ns2\C;
echo C::$a; // In T;Bear in mind that it's perfectly fine to alias namespaces, ie:
<?php
use A\B\C\D\E\User;
new User();
?>
can be also written as:
<?php
use A\B\C\D\E as ENamespace;
new ENamespace\User();
?>
however following will not work:
<?php
use A\B\C\D\E as ENamespace;
use ENamespace\User;
new User();
?>
> PHP Error: Class "ENamespace\User" not foundFor the fifth example (example #5):
When in block scope, it is not an illegal use of use keyword, because it is used for sharing things with traits.