Programming

is_a와 instanceof의 차이점은 무엇입니까?

procodes 2020. 5. 11. 21:11
반응형

is_a와 instanceof의 차이점은 무엇입니까?


나는 그것이 instanceof연산자이고 그것이 is_a방법 이라는 것을 알고 있습니다.

방법이 성능이 느립니까? 무엇을 사용 하시겠습니까?


최신 정보

현재 PHP 5.3.9 의 기능이 is_a()변경되었습니다. 아래의 원래 답변 은 첫 번째 인수로을 수락 is_a() 해야Object 하지만 PHP 버전> = 5.3.9 는 문자열 클래스 이름을 비교할 수 있는 선택적 세 번째 부울 인수 $allow_string(기본값은 false)를 허용합니다.

class MyBaseClass {}
class MyExtendingClass extends MyBaseClass {}

// Original behavior, evaluates to false.
is_a(MyExtendingClass::class, MyBaseClass::class);

// New behavior, evaluates to true.
is_a(MyExtendingClass::class, MyBaseClass::class, true);

사이의 새로운 동작의 차이점 instanceofis_a()instanceof반면, 항상 목표 (확장 클래스를 포함) 지정된 클래스의 객체 인스턴스인지 확인합니다 is_a()에만이 경우 개체가 인스턴스화해야합니다 $allow_string인수의 기본 값으로 설정됩니다 false.


기발한

실제로 는 언어 구조 is_a인 반면 함수 instanceof입니다. is_a(함수 호출을 실행하는 모든 오버 헤드가 있기 때문에) 상당히 느려질 수 있지만 전체 실행 시간은 두 방법 중 최소입니다.

더 이상 5.3에서 더 이상 사용되지 않으므로 걱정할 필요가 없습니다.

그러나 한 가지 차이점이 있습니다. is_a함수는 객체를 매개 변수 1로, 문자열 (변수, 상수 또는 리터럴)을 매개 변수 2로 사용합니다.

is_a($object, $string); // <- Only way to call it

instanceof 객체를 매개 변수 1로 사용하고 클래스 이름 (변수), 객체 인스턴스 (변수) 또는 클래스 식별자 (따옴표없이 작성된 클래스 이름)를 매개 변수 2로 사용할 수 있습니다.

$object instanceof $string;      // <- string class name
$object instanceof $otherObject; // <- object instance
$object instanceof ClassName;    // <- identifier for the class

is_a ()instanceof 의 성능 결과는 다음과 같습니다 .

Test name       Repeats         Result          Performance     
instanceof      10000           0.028343 sec    +0.00%
is_a()          10000           0.043927 sec    -54.98%

테스트 소스는 여기에 있습니다 .


instanceof다른 객체 인스턴스, 클래스 이름 또는 인터페이스와 함께 사용할 수 있습니다. 나는 그것이 is_a()인터페이스 (클래스 이름을 나타내는 문자열 만)와 함께 작동 한다고 생각하지 않지만 그렇게 하면 나를 수정하십시오. (업데이트 : https://gist.github.com/1455148 참조 )

php.net의:

interface MyInterface
{
}

class MyClass implements MyInterface
{
}

$a = new MyClass;
$b = new MyClass;
$c = 'MyClass';
$d = 'NotMyClass';

var_dump($a instanceof $b); // $b is an object of class MyClass
var_dump($a instanceof $c); // $c is a string 'MyClass'
var_dump($a instanceof $d); // $d is a string 'NotMyClass'

출력 :

bool(true)
bool(true)
bool(false)

ChrisF의 답변과 관련하여 is_a() 더 이상 PHP 5.3.0부터 더 이상 사용되지 않습니다 . 나는 이런 것들을 위해 공식 소스를 이용하는 것이 항상 더 안전하다는 것을 알았습니다.

귀하의 질문에 대해 Daniel, 성능 차이에 대해 말할 수는 없지만 그 일부는 가독성과 함께 사용하기가 더 쉽습니다.

또한 수표를 무효화하는 것에 대한 혼란에 대한 토론이 있습니다. 예를 들어, 위해 당신이 할 것입니다 :instanceofis_a()instanceof

<?php
if( !($a instanceof A) ) { //... }
?>

다음에 대한 대 is_a():

<?php
if( !is_a($a, 'A' ) { //... }
?>

또는

<?php
if( is_a($a, 'A') === FALSE) { //... }
?>

편집 ChrisF가 자신의 답변을 삭제 한 것처럼 보이지만 내 답변의 첫 부분은 여전히 ​​유효합니다.


속도 외에도 또 다른 중요한 차이점은 에지 케이스를 처리하는 방법입니다.

is_a($x1, $x2) // fatal error if x2 is not a string nor an object
$x1 instanceof $x2  // returns false even if $x2 is int, undefined, etc.

So, is_a() highlights possible bugs while instanceof suppresses them.


The optimisation is minimal. And micro-optimisations are never a real good answer, in front of the readability, understandability and stability of the code.

( personaly I prefere instanceof, but the choice is yours ;) )

The principal difference is the possibility to use direct class name with instanceof

$a instanceof MyClass

is shorter than

is_a($a, MyClass::class)

( ok… it’s not trivial. )

The syntaxical coloration between instanceof (language structure) and is_a is usefull too (for me). letting function color to bigger operations. And for single use in if, instanceof dosn’t need more parenthesis.

Note : Of course instead of MyClass::class you can use a shorter direct string :

is_a($a,'MyClass')

But use direct string in a code isn’t a good practice.

The syntaxical colloration is better and more usefull if you can make a difference between simple string and classes names. And it's easier to change names with constant classname. Specialy if you use namespace with alias.

So, wy use is_a() ?

For same raison : readability and undestandability. (the choice is yours) Specialy when used with ! or others boolean operators : is_a seems more pratical with parenthesis.

if( $a AND (!is_a ($a, MyClass::class) OR is_a ($a, MyOtherClass::class)) )

is more readable than :

if( $a AND (!( $a instanceof MyClass) OR ($a intanceof MyOtherClass)))

An other good reason is when you need use callback in functions. ( like array_map … ) instanceof isn’t a function, it’s a language construct, so you cannot use it as callback.

In thoses cases, is_a may be usefull


I can't speak for performance -- I haven't measured anything yet -- but depending on what you are attempting, there are limitations with instanceof. Check out my question, just recently, about it:

PHP 'instanceof' failing with class constant

I've ended up using is_a instead. I like the structure of instanceof better (I think it reads nicer) and will continue to use it where I can.


Here are performance results obtained from here:

instanceof is faster.

Functions

function method_1($a = null) { 
    return is_object($a) && is_a($a, 'Example');
}

function method_2($a = null) {
    return is_a((object) $a, 'Example');
}

function method_3($a = null) {
    return $a instanceof 'Example';
}

Times (run 5000 times each)

0.00573397 // method_1(5) 
0.01437402 // method_2(5) 
0.00376201 // method_3(5)

There is a scenario where only is_a() works and instanceof will fail.

instanceof expects a literal class name or a variable that is either an object or a string (with the name of a class) as its right argument.

But if you want to provide the string of a class name from a function call it will not work and result in a syntax error.

However, the same scenario works fine with is_a().

Example:

<?php

function getClassName() : string
{
    return "Foobar";
}

class Foobar
{
    private $xyz;

}

$x = new Foobar();

// this works of course
var_dump($x instanceof Foobar);

// this creates a syntax error
var_dump($x instanceof getClassName());

// this works
var_dump(is_a($x, getClassName()));

This is based on PHP 7.2.14.

참고URL : https://stackoverflow.com/questions/3017684/what-is-the-difference-between-is-a-and-instanceof

반응형