Computer >> 컴퓨터 >  >> 프로그램 작성 >> PHP

PHP 유형 연산자

<시간/>

소개

PHP에서는 주어진 변수가 특정 클래스의 객체인지 여부를 확인할 수 있습니다. 이를 위해 PHP에는 인스턴스가 있습니다. 연산자.

구문

$var instanceof class

이 연산자는 부울 값을 반환합니다. TRUE $var는 클래스의 객체이고, 그렇지 않으면 FALSE를 반환합니다.

예시

다음 예에서 instanceof 연산자는 사용자 정의 테스트 클래스의 주어진 개체가 있는지 확인합니다.

예시

<?php
class testclass{
   //class body
}
$a=new testclass();
if ($a instanceof testclass==TRUE){
   echo "\$a is an object of testclass";
} else {
   echo "\$a is not an object of testclass";
}
?>

출력

다음 결과가 표시됩니다.

$a is an object of testclass

특정 객체가 클래스의 인스턴스가 아닌지 확인하려면 ! 연산자

예시

<?php
class testclass{
   //class body
}
$a=new testclass();
$b="Hello";
if (!($b instanceof testclass)==TRUE){
   echo "\$b is not an object of testclass";
} else {
   echo "\$b is an object of testclass";
}
?>

출력

다음 결과가 표시됩니다.

$b is not an object of testclass

instanceof 연산자는 변수가 부모 클래스의 객체인지 여부도 확인합니다.

예시

<?php
class base{
   //class body
}
class testclass extends base {
   //class body
}
$a=new testclass();
var_dump($a instanceof base)
?>

출력

다음 결과가 표시됩니다.

bool(true)

또한 변수가 intrface의 인스턴스인지 여부를 확인할 수 있습니다.

예시

<?php
interface base{
}
class testclass implements base {
   //class body
}
$a=new testclass();
var_dump($a instanceof base)
?>

출력

다음 결과가 표시됩니다.

bool(true)