키워드 "use"는 PHP에서 어떻게 작동하며 클래스를 가져올 수 있습니까?
class 파일이 Resp
있습니다. 경로는 다음과 같습니다
C:\xampp\htdocs\One\Classes\Resp.php
그리고 나는이 index.php
이 디렉토리에있는 파일을 :
C:\xampp\htdocs\Two\Http\index.php
이 index.php
파일에서 클래스를 인스턴스화하고 싶습니다 Resp
.
$a = new Resp();
클래스를 사용 하여 파일을 포함하기 위해 require
또는 include
키워드를 사용할 수 있다는 것을 알고 있습니다 .
require("One\Classes\Resp.php"); // I've set the include_path correctly already ";C:\xampp\htdocs". It works.
$a = new Resp();
하지만 사용하지 않고 클래스를 가져올 require
나 include
. use
키워드 작동 방식을 이해하려고 합니다. 이 단계를 시도했지만 아무것도 작동하지 않습니다.
use One\Classes\Resp;
use xampp\htdocs\One\Classes\Resp;
use htdocs\One\Classes\Resp;
use One\Classes;
use htdocs\One\Classes; /* nothing works */
$a = new Resp();
그것은 말한다 :
Fatal error: Class 'One\Classes\Resp' not found in C:\xampp\htdocs\Two\Http\index.php
키워드는 어떻게 use
작동합니까? 클래스를 가져 오는 데 사용할 수 있습니까?
use
아무것도 포함하지 않습니다. 지정된 네임 스페이스 (또는 클래스)를 현재 범위로 가져옵니다.
당신이 원하는 경우 클래스는 자동으로 적재된다 -에 대해 읽어 자동 로딩
아니요, use
키워드를 사용 하여 수업을 가져올 수 없습니다 . include
/ require
문 을 사용해야 합니다. PHP 자동 로더를 사용하더라도 여전히 자동 로더는 내부 include
또는 require
내부 를 사용해야합니다 .
사용 목적 키워드 :
동일한 이름을 가진 두 개의 클래스가있는 경우를 고려하십시오. 이상하게 느껴지 겠지만 큰 MVC 구조로 작업 할 때 발생합니다. 이름이 같은 클래스가 두 개인 경우 다른 네임 스페이스에 넣으십시오. 이제 자동 로더가 두 클래스를 모두로드 할 때 (by by require
)를 고려하고 클래스 객체를 사용하려고합니다. 이 경우 컴파일러는 두 클래스 중 어떤 클래스 객체를로드할지 혼동합니다. 컴파일러가 결정을 내리는 데 도움을주기 위해 use
명령문을 사용하여 어느 것이 사용될 것인지 결정할 수 있습니다.
현재 주요 프레임 워크 사용을 include
또는 require
경유 composer
와psr
1) 작곡가
2) PSR-4 오토로더
그들을 통해 가면 더 도움이 될 수 있습니다. 별명을 사용하여 정확한 클래스를 처리 할 수도 있습니다. 이름이 같은 두 개의 클래스가 있고 Mailer
서로 다른 네임 스페이스 가 있다고 가정 해 봅시다 .
namespace SMTP;
class Mailer{}
과
namespace Mailgun;
class Mailer{}
그리고 두 Mailer 클래스를 동시에 사용하려면 별명을 사용할 수 있습니다.
use SMTP\Mailer as SMTPMailer;
use Mailgun\Mailer as MailgunMailer;
나중에 클래스 객체에 액세스하려면 코드에서 다음을 수행하십시오.
$smtp_mailer = new SMTPMailer;
$mailgun_mailer = new MailgunMailer;
원래 클래스를 참조합니다.
일부 클래스는 비슷한 클래스 이름이없고 use
키워드를 사용하지 않는다고 혼동 될 수 있습니다 . 글쎄, 당신은 인수로 사용될 클래스와 함께 명령문이 실행될 __autoload($class)
때 자동으로 호출되는 함수를 사용할 use
수 있으며, 필요할 때 런타임에 클래스를로드하는 데 도움이 될 수 있습니다.
Refer this answer to know more about class autoloader.
Don’t overthink what a Namespace is.
Namespace is basically just a Class prefix (like directory in Operating System) to ensure the Class path uniqueness.
Also just to make things clear, the use statement is not doing anything only aliasing your Namespaces so you can use shortcuts or include Classes with the same name but different Namespace in the same file.
E.g:
// You can do this at the top of your Class
use Symfony\Component\Debug\Debug;
if ($_SERVER['APP_DEBUG']) {
// So you can utilize the Debug class it in an elegant way
Debug::enable();
// Instead of this ugly one
// \Symfony\Component\Debug\Debug::enable();
}
If you want to know how PHP Namespaces and autoloading (the old way as well as the new way with Composer) works, you can read the blog post I just wrote on this topic: https://enterprise-level-php.com/2017/12/25/the-magic-behind-autoloading-php-files-using-composer.html
You'll have to include/require the class anyway, otherwise PHP won't know about the namespace.
You don't necessary have to do it in the same file though. You can do it in a bootstrap file for example. (or use an autoloader, but that's not the topic actually)
The issue is most likely you will need to use an auto loader that will take the name of the class (break by '\' in this case) and map it to a directory structure.
You can check out this article on the autoloading functionality of PHP. There are many implementations of this type of functionality in frameworks already.
I've actually implemented one before. Here's a link.
I agree with Green, Symfony needs namespace, so why not use them ?
This is how an example controller class starts:
namespace Acme\DemoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class WelcomeController extends Controller { ... }
Can I use it to import classes?
You can't do it like that besides the examples above. You can also use the keyword use
inside classes to import traits, like this:
trait Stuff {
private $baz = 'baz';
public function bar() {
return $this->baz;
}
}
class Cls {
use Stuff; // import traits like this
}
$foo = new Cls;
echo $foo->bar(); // spits out 'baz'
The use
keyword is for aliasing in PHP and it does not import the classes. This really helps
1) When you have classes with same name in different namespaces
2) Avoid using really long class name over and over again.
Using the keyword "use" is for shortening namespace literals. You can use both with aliasing and without it. Without aliasing you must use last part of full namespace.
<?php
use foo\bar\lastPart;
$obj=new lastPart\AnyClass(); //If there's not the line above, a fatal error will be encountered.
?>
Namespace is use to define the path to a specific file containing a class e.g.
namespace album/className;
class className{
//enter class properties and methods here
}
You can then include this specific class into another php file by using the keyword "use" like this:
use album/className;
class album extends classname {
//enter class properties and methods
}
NOTE: Do not use the path to the file containing the class to be implements, extends of use to instantiate an object but only use the namespace.
'IT story' 카테고리의 다른 글
Matplotlib (pyplot) savefig는 빈 이미지를 출력합니다. (0) | 2020.07.06 |
---|---|
Android의 새로운 하단 탐색 모음 또는 BottomNavigationView (0) | 2020.07.06 |
NSInteger에 대한 NSLog / printf 지정자? (0) | 2020.07.06 |
C ++ 벡터를 어떻게 되돌 립니까? (0) | 2020.07.06 |
Android : Handler ()는 언제 사용해야하며 언제 Thread를 사용해야합니까? (0) | 2020.07.06 |