Php get type class

gettype

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

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

Переменная, у которой проверяется тип.

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

  • » boolean «
  • » integer «
  • » double » (по историческим причинам в случае типа float возвращается «double», а не просто «float»)
  • » string «
  • » array «
  • » object «
  • » resource «
  • » NULL «
  • «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

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

  • 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() — Проверяет, существует ли метод в данном классе

Источник

get_class

Возвращает имя класса, экземпляром которого является объект object .

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

Тестируемый объект. Внутри класса этот параметр может быть опущен.

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

Возвращает имя класса, к которому принадлежит экземпляр object . Возвращает FALSE , если object не является объектом.

Если параметр object опущен внутри класса, будет возвращено имя этого класса.

Ошибки

Если get_class() будет вызвана с чем-то другим, не являющимся объектом, будет вызвана ошибка уровня E_WARNING .

Читайте также:  Название страницы

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

Версия Описание
5.3.0 NULL стал значением по умолчанию для параметра object , поэтому передача NULL в object теперь имеет тот же самый эффект, как и отсутствие какой-либо передачи вообще.

Примеры

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

class foo function name ()
echo «My name is » , get_class ( $this ) , «\n» ;
>
>

// создание объекта
$bar = new foo ();

// внешний вызов
echo «Its name is » , get_class ( $bar ) , «\n» ;

// внутренний вызов
$bar -> name ();

Результат выполнения данного примера:

Its name is foo My name is foo

Пример #2 Использование get_class() в родительском классе

abstract class bar public function __construct ()
var_dump ( get_class ( $this ));
var_dump ( get_class ());
>
>

Результат выполнения данного примера:

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

  • get_called_class() — Имя класса, полученное с помощью позднего статического связывания
  • get_parent_class() — Возвращает имя родительского класса для объекта или класса
  • gettype() — Возвращает тип переменной
  • is_subclass_of() — Проверяет, содержит ли объект в своем дереве предков указанный класс

Источник

Get Class Name in PHP

Get Class Name in PHP

  1. Use Class Name Resolution to Get Class Name in PHP
  2. Use __CLASS__ Constant to Get Class Name in PHP
  3. Use get_class() Function to Get Class Name in PHP
  4. Use Reflection Class to Get Class Name in PHP
  5. Use ::class on Object to Get Class Name in PHP

This tutorial will discuss how to get a PHP class name with class name resolution, PHP __CLASS__ constant, and the get_class() method. You will learn its usage for the class name resolution in and out of a class.

Use Class Name Resolution to Get Class Name in PHP

You can get a class name via class name resolution when you have a namespace in your code. The result is a Fully Qualified Class Name (FQCN).

This feature is available in PHP as ClassName::class . It is useful when you have a namespace in your PHP.

In the following code example, the class name resolution via ClassName::class will return the class name of the associated class:

php  namespace YourNameSpace;   // Define a class  class HelloClassName <>   // Get the class name from ::class  echo HelloClassName::class; ?> 
YourNameSpace\HelloClassName 

If you want to use this feature in a class method, you can get the class name via the static method. You’ll write this as static::class .

The next code example shows how to get a class name in a class method.

php  namespace YourNameSpace;   // Define the class name  class HelloClassName   /**  * Define a function that returns  * the class name via static::class  */  public function getClassName()   return static::class;  >  >   // Create a new object  $hello_class_name = new HelloClassName();   // Get the class name  echo $hello_class_name->getClassName(); ?> 
YourNameSpace\HelloClassName 

Use __CLASS__ Constant to Get Class Name in PHP

The __CLASS__ constant is part of the PHP predefined constant. You can use it within a class to get a class name.

The following code will get the class name via the __CLASS__ constant.

php  // Define the class  class Hello   // This function will return the  // class name  function HelloName ()  return __CLASS__;  >  >   // Create a new object  $hello_object= new Hello();   // Get the class name  echo $hello_object->HelloName(); ?> 

Use get_class() Function to Get Class Name in PHP

PHP provides a get_class() function. This function will return the class name. You can use it in procedural and object-oriented programming. First, we’ll take a look at the procedural style.

The next code block defines a class with a single function. The function within the class will return the class name when its argument is the this keyword.

To get the class name, you create an object from the class; then, you pass the object’s name to get_class() .

php  // Define a class  class Hello   function class_name()   echo "The class name is: ", get_class($this);  >  >   // Create a new object  $new_hello_object = new Hello();   // Get the class name  $new_hello_object->class_name();   // Also, you can get the class name  // via an external call  // echo get_class($new_hello_object);  ?> 

At first, for the OOP style, you can return the get_class() function from a static class.

php  // Define a class  class Hello   public static function class_name()   return get_class();  >  >   // Get the class name  $class_name = Hello::class_name();   echo $class_name; ?> 

This method has its limitations because when you extend the class, the extended class will return the name of the parent class and not the extended class. To solve this, you can use get_called_class() .

The get_called class() function relies on Late Static Binding. With this function, PHP will return the name of the calling class. It solves the situation where the extended class returns the name of its parent class rather than its own.

php  // Define a class  class Hello    // A static function that returns the  // name of the class that calls it  public static function called_class_name()   return get_called_class();  >   // This function will return the  // defining class name  public static function get_defining_class()   return get_class();  > >  class ExtendHello extends Hello   >  $hello_class_name = Hello::called_class_name(); $extended_class_name = ExtendHello::called_class_name(); $extend_hello_parent_class = ExtendHello::get_defining_class();  echo "Hello class name: " . $hello_class_name . "\n"; echo "Extended Hello class name: " . $extended_class_name . "\n"; echo "Extended Hello parent class name: " . $extend_hello_parent_class . "\n"; ?> 
Hello class name: Hello Extended Hello class name: ExtendHello Extended Hello parent class name: Hello 

Use Reflection Class to Get Class Name in PHP

Reflection Class is a concise way to get a class name in PHP. You create a class; within this class, create a function that returns a new Reflection class.

The Reflection class should have its argument set to $this . Afterward, you can get the class name via the getShortName() method available with the Reflection class.

php  // Define a class  class Hello   // A function that returns the class  // name via reflection  public function HelloClassName()   return (new \ReflectionClass($this))->getShortName();  >  >   // Create a new class name  $hello_class_name = new Hello();   // Get the class name  echo $hello_class_name->HelloClassName(); ?> 

Use ::class on Object to Get Class Name in PHP

The ::class feature worked on classes before PHP 8. Since PHP, when you create an object from a class, you can get the class name from the created object with ::class .

You’ll find an example in the following code block.

php  namespace YourNameSpace;   // define the class  class HelloClassName    >   // Create a new object  $hello_class_name = new HelloClassName();   // Get the class name from the object  // via ::class  echo $hello_class_name::class; ?> 
YourNameSpace\HelloClassName 

Habdul Hazeez is a technical writer with amazing research skills. He can connect the dots, and make sense of data that are scattered across different media.

Related Article — PHP Class

Источник

Оцените статью