programing

PHP의 ::class란 무엇입니까?

randomtip 2022. 11. 21. 22:54
반응형

PHP의 ::class란 무엇입니까?

이 뭐죠?::classPHP 표기법?

빠른 Google 검색은 구문의 특성 때문에 아무것도 반환하지 않습니다.

결장급

이 표기법을 사용하면 어떤 장점이 있나요?

protected $commands = [
    \App\Console\Commands\Inspire::class,
];

SomeClass::class의 정규화된 이름을 반환한다.SomeClass네임스페이스를 포함합니다.이 기능은 PHP 5.5에서 구현되었습니다.

문서: http://php.net/manual/en/migration55.new-features.php#migration55.new-features.class-name

그것은 두 가지 이유로 매우 유용합니다.

  • 더 이상 클래스 이름을 문자열로 저장할 필요가 없습니다.따라서 코드를 리팩터링할 때 많은 IDE가 이러한 클래스 이름을 검색할 수 있습니다.
  • 를 사용할 수 있습니다.use키워드를 사용하여 클래스를 해결합니다.클래스 이름을 모두 쓸 필요는 없습니다.

예를 들어 다음과 같습니다.

use \App\Console\Commands\Inspire;

//...

protected $commands = [
    Inspire::class, // Equivalent to "App\Console\Commands\Inspire"
];

업데이트:

이 기능은 레이트 스태틱바인딩에도 도움이 됩니다.

를 사용하는 대신__CLASS__매직 상수, 당신은 그것을 사용할 수 있습니다.static::classfeature를 사용하여 부모 클래스 내에서 파생된 클래스의 이름을 가져옵니다.예를 들어 다음과 같습니다.

class A {

    public function getClassName(){
        return __CLASS__;
    }

    public function getRealClassName() {
        return static::class;
    }
}

class B extends A {}

$a = new A;
$b = new B;

echo $a->getClassName();      // A
echo $a->getRealClassName();  // A
echo $b->getClassName();      // A
echo $b->getRealClassName();  // B

class는 php에서 제공하는 특별한 것으로, 완전한 클래스 이름은 완전 수식입니다.

http://php.net/manual/en/migration55.new-features.php#migration55.new-features.class-name 를 참조해 주세요.

<?php

class foo {
    const test = 'foobar!';
}

echo foo::test; // print foobar!

어떤 카테고리에 속하는지 궁금할 경우(언어 구성 등),

그냥 상수에요.

PHP는 이를 "특별 상수"라고 부릅니다.컴파일 시에 PHP에 의해 제공되기 때문에 특별합니다.

특수 :: 클래스 상수는 PHP 5.5.0에서 사용할 수 있으며 컴파일 시 완전 수식 클래스 이름 해결이 가능합니다.이것은 namesthed 클래스에 도움이 됩니다.

https://www.php.net/manual/en/language.oop5.constants.php

다음 사항을 사용하시기 바랍니다.

if ($whatever instanceof static::class) {...}

그러면 구문 오류가 발생합니다.

unexpected 'class' (T_CLASS), expecting variable (T_VARIABLE) or '$'

대신 다음 작업을 수행할 수 있습니다.

if ($whatever instanceof static) {...}

또는

$class = static::class;
if ($whatever instanceof $class) {...}

언급URL : https://stackoverflow.com/questions/30770148/what-is-class-in-php

반응형