Как узнать тип переменной php
Перейти к содержимому

Как узнать тип переменной php

  • автор:

gettype

Возвращает тип PHP-переменной value . Для проверки типа переменной используйте функции is_* .

Список параметров

Возвращаемые значения

  • «boolean»
  • «integer»
  • «double» (по историческим причинам в случае типа float возвращается «double» , а не просто «float» )
  • «string»
  • «array»
  • «object»
  • «resource»
  • «resource (closed)» с PHP 7.2.0
  • «NULL»
  • «unknown type»

Список изменений

Версия Описание
7.2.0 Для закрытых ресурсов теперь возвращается ‘resource (closed)’ . Ранее для закрытых ресурсов возвращалось ‘unknown type’ .

Примеры

Пример #1 Пример использования gettype()

$data = array( 1 , 1. , NULL , new stdClass , ‘foo’ );

foreach ( $data as $value ) echo gettype ( $value ), «\n» ;
>

Вывод приведённого примера будет похож на:

integer double NULL object string

Смотрите также

  • get_debug_type() — Возвращает имя типа переменной в виде, подходящем для отладки
  • settype() — Задаёт тип переменной
  • get_class() — Возвращает имя класса, которому принадлежит объект
  • is_array() — Определяет, представляет ли собой переменная массив
  • is_bool() — Проверяет, представляет ли собой переменная логическое значение
  • is_callable() — Проверяет, что значение может быть вызвано как функция в текущей области видимости
  • is_float() — Проверяет, представляет ли собой переменная число с плавающей точкой
  • is_int() — Проверяет, представляет ли собой переменная целое число
  • is_null() — Проверяет, равно ли значение переменной null
  • is_numeric() — Проверяет, содержит ли переменная число или числовую строку
  • is_object() — Проверяет, представляет ли собой переменная объект
  • is_resource() — Проверяет, представляет ли собой переменная ресурс
  • is_scalar() — Проверяет, представляет ли собой переменная скаляр
  • is_string() — Проверяет, представляет ли собой тип переменной строку
  • function_exists() — Возвращает true, если указанная функция определена
  • method_exists() — Проверяет, существует ли метод в классе

Как узнать тип переменной php

Для получения типа переменной применяется функция gettype() , которая возвращает название типа переменной, например, integer (целое число), double (число с плавающей точкой), string (строка), boolean (логическое значение), null , array (массив), object (объект) или unknown type . Например:

"; echo gettype($b); // string ?>

Также есть ряд специальных функций, которые возвращают true или false в зависимости от того, представляет ли переменная определенный тип:

  • is_integer($a) : возвращает значение true , если переменная $a хранит целое число
  • is_string($a) : возвращает значение true , если переменная $a хранит строку
  • is_double($a) : возвращает значение true , если переменная $a хранит действительное число
  • is_numeric($a) : возвращает значение true , если переменная $a представляет целое или действительное число или является строковым представлением числа. Например:

$a = 10; $b = "10"; echo is_numeric($a); echo "
"; echo is_numeric($b);

Установка типа. Функция settype()

С помощью функции settype() можно установить для переменной определенный тип. Она принимает два параметра: settype(«Переменная», «Тип») . В качестве первого параметра используется переменная, тип которой надо установить, а в качестве второго — строковое описание типа, которое возвращается функцией gettype() .

Если удалось установить тип, то функция возвращает true , если нет — то значение false .

Например, установим для переменной целочисленный тип:

Поскольку переменная $a представляет действительное число 10.7, то его вполне можно преобразовать в целое число через отсечение дробной части. Поэтому в данном случае функция settype() возвратит true .

Преобразование типов

По умолчанию PHP при необходимости автоматически преобразует значение переменной из одного типа в другой. По этой причине явные преобразования в PHP не так часто требуются. Тем не менее мы можем их применять.

Для явного преобразования перед переменной в скобках указыется тип, в который надо выполнить преобразование:

$boolVar = false; $intVar = (int)$boolVar; // 0 echo "boolVar = $boolVar
intVar = $intVar";

В данном случае значение «false» пробразуется в значение типа int , которое будет храниться в переменной $intVar . А именно значение false преобразуется в число 0. После этого мы сможем использовать данное значение как число.

При использовании выражения echo для вывода на страницу передаваемые значения автоматически преобразуются в строку. И поскольку переменная boolVar равна false , ее значение будет преобазовано в пустую строку. Тогда как значение 0 преобразуется в строку «0».

В PHP могут применяться следующие преобразования:

  • (int), (integer) : преобразование в int (в целое число)
  • (bool), (boolean) : преобразование в bool
  • (float), (double), (real) : преобразование в float
  • (string) : преобразование в строку
  • (array) : преобразование в массив
  • (object) : преобразование в object

Как проверить тип переменной (PHP)

В PHP для определения типа переменной существует функция string gettype(mixed var) , которая возвращает название типа переменной в виде строки: null, boolean, integer, string, double, array, object, resource.

Пример

Определим по одной переменной каждого вида, и установим соответствующее переменной значение, а затем выведем результат проверки каждой переменной на экран.

Результат

NULL
boolean
integer
double
string
array
resource
object

Как видно из результата, функция gettype() отлично справляется с поставленной задачей.

Примечание

Если тип переменной float , то результат функции будет double .

✖ ❤ Мне помогла статья 5 оценок
13506 просмотров 1 комментарий Артём Фёдоров 10 апреля 2011

Категории

Читайте также

  • Переменная является числом (PHP)
  • Как определить браузер в PHP
  • Определить поискового бота (PHP)
  • Как проверить права доступа (PHP)
  • Преобразовать массив в объект (PHP)
  • Проверка электронной почты (PHP)
  • Деление без остатка (PHP)
  • Первые N символов строки цифры (PHP)
  • Дата изменения файла (PHP)
  • Singleton Trait (PHP)
  • Редирект (PHP)
  • Склонение числительных на PHP

Комментарии

09 сентября 2022 в 17:27

//Проверка переменной на число
$a = «4»;
if(gettype($a) === ‘integer’) echo ‘true’;
>else echo «Ложь» .$a. » Это «;
echo gettype($a);
>

Написать комментарий
© Экспэнч 2010-2024
При полном или частичном копировании статей сайта указывайте пожалуйста ссылку на источник
Хотите узнать больше информации, пишите на: artem@expange.ru

Вход на сайт

Введите данные указанные при регистрации:

Социальные сети

Вы можете быстро войти через социальные сети:

Как узнать тип переменной php

Posting this so the word typeof appears on this page, so that this page will show up when you google ‘php typeof’. . yeah, former Java user.

11 years ago

Checking an object is not an instance of a class, example #3 uses extraneous parentheses.

var_dump (!( $a instanceof stdClass ));
?>

Because instanceof has higher operator precedence than ! you can just do

var_dump ( ! $a instanceof stdClass );
?>

12 years ago

I don’t see any mention of «namespaces» on this page so I thought I would chime in. The instanceof operator takes FQCN as second operator when you pass it as string and not a simple class name. It will not resolve it even if you have a `use MyNamespace\Bar;` at the top level. Here is what I am trying to say:

## testinclude.php ##
namespace Bar1 ;
class Foo1 < >
>
namespace Bar2 ;
class Foo2 < >
>
?>
## test.php ##
include( ‘testinclude.php’ );
use Bar1\Foo1 as Foo ;
$foo1 = new Foo (); $className = ‘Bar1\Foo1’ ;
var_dump ( $foo1 instanceof Bar1\Foo1 );
var_dump ( $foo1 instanceof $className );
$className = ‘Foo’ ;
var_dump ( $foo1 instanceof $className );
use Bar2\Foo2 ;
$foo2 = new Foo2 (); $className = ‘Bar2\Foo2’ ;
var_dump ( $foo2 instanceof Bar2\Foo2 );
var_dump ( $foo2 instanceof $className );
$className = ‘Foo2’ ;
var_dump ( $foo2 instanceof $className );
?>
## stdout ##
bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)

10 years ago

You are also able to compare 2 objects using instanceOf. In that case, instanceOf will compare the types of both objects. That is sometimes very useful:

class A < >
class B

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

echo $a instanceOf $a ; // true
echo $a instanceOf $b ; // false
echo $a instanceOf $a2 ; // true

2 years ago

if you have only class names (not objects) you can use that snippet: https://3v4l.org/mUKUC
interface i <>
class a implements i <>

var_dump ( a ::class instanceof i ); // false
var_dump ( in_array ( i ::class, class_implements ( a ::class), true )); // true

6 years ago

Doing $a instanceof stdClass from inside a namespace will not work on its own.

You will have to do:

if ( $a instanceof \stdClass )
?>

15 years ago

Example #5 could also be extended to include.

var_dump($a instanceof MyInterface);

The new result would be

So — instanceof is smart enough to know that a class that implements an interface is an instance of the interface, not just the class. I didn’t see that point made clearly enough in the explanation at the top.

12 years ago

If you want to test if a classname is an instance of a class, the instanceof operator won’t work.

$classname = ‘MyClass’ ;
if( $classname instanceof MyParentClass ) echo ‘Child of it’ ;
else echo ‘Not child of it’ ;
?>

Will always output
Not child of it

You must use a ReflectionClass :
$classname = ‘MyClass’ ;
$myReflection = new ReflectionClass ( $classname );
if( $myReflection -> isSubclassOf ( ‘MyParentClass’ )) echo ‘Child of it’ ;
else echo ‘Not child of it’ ;
?>

Will output the good result.
If you’re testing an interface, use implementsInterface() instead of isSublassOf().

15 years ago

You can use «self» to reference to the current class:

class myclass <
function mymethod ( $otherObject ) <
if ( $otherObject instanceof self ) <
$otherObject -> mymethod ( null );
>
return ‘works!’ ;
>
>

$a = new myclass ();
print $a -> mymethod ( $a );
?>

11 years ago

SIMPLE, CLEAN, CLEAR use of the instanceof OPERATOR

First, define a couple of simple PHP Objects to work on — I’ll introduce Circle and Point. Here’s the class definitions for both:

class Circle
protected $radius = 1.0 ;

/*
* This function is the reason we are going to use the
* instanceof operator below.
*/
public function setRadius ( $r )
$this -> radius = $r ;
>

public function __toString ()
return ‘Circle [radius=’ . $this -> radius . ‘]’ ;
>
>

class Point
protected $x = 0 ;
protected $y = 0 ;

/*
* This function is the reason we are going to use the
* instanceof operator below.
*/
public function setLocation ( $x , $y )
$this -> x = $x ;
$this -> y = $y ;
>

public function __toString ()
return ‘Point [x=’ . $this -> x . ‘, y=’ . $this -> y . ‘]’ ;
>
>

?>

Now instantiate a few instances of these types. Note, I will put them in an array (collection) so we can iterate through them quickly.

$myCollection = array( 123 , ‘abc’ , ‘Hello World!’ ,
new Circle (), new Circle (), new Circle (),
new Point (), new Point (), new Point ());

$i = 0 ;
foreach( $myCollection AS $item )
/*
* The setRadius() function is written in the Circle class
* definition above, so make sure $item is an instance of
* type Circle BEFORE calling it AND to avoid PHP PMS!
*/
if( $item instanceof Circle )
$item -> setRadius ( $i );
>

/*
* The setLocation() function is written in the Point class
* definition above, so make sure $item is an instance of
* type Point BEFORE calling it AND to stay out of the ER!
*/
if( $item instanceof Point )
$item -> setLocation ( $i , $i );
>

echo ‘$myCollection[‘ . $i ++ . ‘] = ‘ . $item . ‘
‘ ;
>

?>

$myCollection[0] = 123
$myCollection[1] = abc
$myCollection[2] = Hello World!
$myCollection[3] = Circle [radius=3]
$myCollection[4] = Circle [radius=4]
$myCollection[5] = Circle [radius=5]
$myCollection[6] = Point [x=6, y=6]
$myCollection[7] = Point [x=7, y=7]
$myCollection[8] = Point [x=8, y=8]

6 years ago

If you want to use «$foo instanceof $bar» to determine if two objects are the same class, remember that «instanceof» will also evaluate to true if $foo is an instance of a _subclass_ of $bar’s class.

If you really want to see if they are the _same_ class, then they both have to be instances of each other’s class. That is:

( $foo instanceof $bar && $bar instanceof $foo )

?>

Consider it an alternative to «get_class($bar) == get_class($foo)» that avoids the detour through to string lookups and comparisons.

4 years ago

Using an undefined variable will result in an error.

If variable is in doubt, one must prequalify:

if ( isset( $MyInstance ) and $MyInstance instanceof MyClass ) .

16 years ago

Response to vinyanov at poczta dot onet dot pl:

You mentionned «the instanceof operator will not accept a string as its first operand». However, this behavior is absolutely right and therefore, you’re misleading the meaning of an instance.

means «the class named ClassA is an instance of the class named ClassB». This is a nonsense sentence because when you instanciate a class, you ALWAYS obtain an object. Consequently, you only can ask if an object is an instance of a class.

I believe asking if «a ClassA belongs to a ClassB» (or «a ClassA is a class of (type) ClassB») or even «a ClassA is (also) a ClassB» is more appropriate. But the first is not implemented and the second only works with objects, just like the instanceof operator.

Plus, I just have tested your code and it does absolutely NOT do the same as instanceof (extended to classes)! I can’t advise anyone to reuse it. The use of raises a warning «include_once(Object id #1.php) …» when using __autoload (trying to look for $instanceOfA as if it was a class name).

Finally, here is a fast (to me) sample function code to verify if an object or class:

16 years ago

The PHP parser generates a parse error on either of the two lines that are commented out here.
Apparently the ‘instanceof’ construct will take a string variable in the second spot, but it will NOT take a string. lame

class Bar <>
$b = new Bar;
$b_class = «Bar»;
var_export($b instanceof Bar); // this is ok
var_export($b instanceof $b_class); // this is ok
//var_export($f instanceof «Bar»); // this is syntactically illegal
//var_export($f instanceof ‘Bar’); // this is syntactically illegal

16 years ago

Cross version function even if you are working in php4
(instanceof is an undefined operator for php4)

function isMemberOf($classename) $ver = floor(phpversion());
if($ver > 4) $instanceof = create_function (‘$obj,$classname’,’return $obj instanceof $classname;’);
return $instanceof($this,$classname);
> else // Php4 uses lowercase for classname.
return is_a($this, strtolower($classname));
>
> // end function isMemberOf

17 years ago

Please note: != is a separate operator with separate semantics. Thinking about language grammar it’s kind of ridicilous to negate an operator. Of course, it’s possible to negate the result of a function (like is_a()), since it isn’t negating the function itself or its semantics.

instanceof is a binary operator, and so used in binary terms like this

terma instanceof termb

while ! (negation) is a unary operator and so may be applied to a single term like this

And a term never consists of an operator, only! There is no such construct in any language (please correct me!). However, instanceof doesn’t finally support nested terms in every operand position («terma» or «termb» above) as negation does:

So back again, did you ever write

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *