Php class data types

Php class data types

While waiting for native support for typed arrays, here are a couple of alternative ways to ensure strong typing of arrays by abusing variadic functions. The performance of these methods is a mystery to the writer and so the responsibility of benchmarking them falls unto the reader.

PHP 5.6 added the splat operator (. ) which is used to unpack arrays to be used as function arguments. PHP 7.0 added scalar type hints. Latter versions of PHP have further improved the type system. With these additions and improvements, it is possible to have a decent support for typed arrays.

function typeArrayNullInt (? int . $arg ): void >

function doSomething (array $ints ): void (function (? int . $arg ) <>)(. $ints );
// Alternatively,
( fn (? int . $arg ) => $arg )(. $ints );
// Or to avoid cluttering memory with too many closures
typeArrayNullInt (. $ints );

function doSomethingElse (? int . $ints ): void /* . */
>

$ints = [ 1 , 2 , 3 , 4 , null ];
doSomething ( $ints );
doSomethingElse (. $ints );
?>

Both methods work with all type declarations. The key idea here is to have the functions throw a runtime error if they encounter a typing violation. The typing method used in doSomethingElse is cleaner of the two but it disallows having any other parameters after the variadic parameter. It also requires the call site to be aware of this typing implementation and unpack the array. The method used in doSomething is messier but it does not require the call site to be aware of the typing method as the unpacking is performed within the function. It is also less ambiguous as the doSomethingElse would also accept n individual parameters where as doSomething only accepts an array. doSomething’s method is also easier to strip away if native typed array support is ever added to PHP. Both of these methods only work for input parameters. An array return value type check would need to take place at the call site.

Читайте также:  Web developer or java developers

If strict_types is not enabled, it may be desirable to return the coerced scalar values from the type check function (e.g. floats and strings become integers) to ensure proper typing.

same data type and same value but first function declare as a argument type declaration and return int(7)
and second fucntion declare as a return type declaration but return int(8).

function argument_type_declaration(int $a, int $b) return $a+$b;
>

function return_type_declaration($a,$b) :int return $a+$b;
>

Источник

PHP Data Types

Variables can store data of different types, and different data types can do different things.

PHP supports the following data types:

  • String
  • Integer
  • Float (floating point numbers — also called double)
  • Boolean
  • Array
  • Object
  • NULL
  • Resource

PHP String

A string is a sequence of characters, like «Hello world!».

A string can be any text inside quotes. You can use single or double quotes:

Example

PHP Integer

An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.

  • An integer must have at least one digit
  • An integer must not have a decimal point
  • An integer can be either positive or negative
  • Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation

In the following example $x is an integer. The PHP var_dump() function returns the data type and value:

Example

PHP Float

A float (floating point number) is a number with a decimal point or a number in exponential form.

In the following example $x is a float. The PHP var_dump() function returns the data type and value:

Example

PHP Boolean

A Boolean represents two possible states: TRUE or FALSE.

Booleans are often used in conditional testing. You will learn more about conditional testing in a later chapter of this tutorial.

PHP Array

An array stores multiple values in one single variable.

In the following example $cars is an array. The PHP var_dump() function returns the data type and value:

Example

You will learn a lot more about arrays in later chapters of this tutorial.

PHP Object

Classes and objects are the two main aspects of object-oriented programming.

A class is a template for objects, and an object is an instance of a class.

When the individual objects are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.

Let’s assume we have a class named Car. A Car can have properties like model, color, etc. We can define variables like $model, $color, and so on, to hold the values of these properties.

When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.

If you create a __construct() function, PHP will automatically call this function when you create an object from a class.

Example

class Car public $color;
public $model;
public function __construct($color, $model) $this->color = $color;
$this->model = $model;
>
public function message() return «My car is a » . $this->color . » » . $this->model . «!»;
>
>

$myCar = new Car(«black», «Volvo»);
echo $myCar -> message();
echo «
«;
$myCar = new Car(«red», «Toyota»);
echo $myCar -> message();
?>

PHP NULL Value

Null is a special data type which can have only one value: NULL.

A variable of data type NULL is a variable that has no value assigned to it.

Tip: If a variable is created without a value, it is automatically assigned a value of NULL.

Variables can also be emptied by setting the value to NULL:

Example

PHP Resource

The special resource type is not an actual data type. It is the storing of a reference to functions and resources external to PHP.

A common example of using the resource data type is a database call.

We will not talk about the resource type here, since it is an advanced topic.

Источник

Php class data types

В отличие от ряда языков программирования в PHP при определении переменных или параметров функций можно не указывать тип данных. Однако в принципе PHP в ряде ситуаций — при определении свойств классов, параметров или возвращаемого значения функций — позволяет указать тип данных. Установка типа данных позволит избежать ситуаций, когда в программу будут переданы данные не тех типов, которые ожидалась разработчиком.

function isPositive($number) < return $number >0; > $result = isPositive("-Youdontknowwhoiam"); if($result) echo "положительное"; else echo "отрицательное или равно нулю";

В данном случае функция isPositive() очевидно ожидает, что в качестве параметра будет передано число, чтобы установить, больше оно нуля или нет. Тем не менее при вызове функции мы можем передать в нее произвольное значение. Чтобы оградиться от подобным ситуаций необходимо явным образом указать, что функция может принимать только число, то есть типизировать параметр функции.

Определение типа

Какие определения типов могут использоваться при типизации:

  • bool : допустимые значения true и false
  • float : значение должно число с плавающей точкой
  • int : значение должно представлять целое число
  • string : значение должно представлять строку
  • mixed : любое значение
  • callable : значение должно представлять функцию
  • array : значение должно представлять массив
  • iterable : значение должно представлять массив или класс, который реализует интерфейс Traversable . Применяется при переборе в цикле foreach
  • Имя класса: объект должен представлять данный класс или его производные классы
  • Имя интерфейса: объект должен представлять класс, который реализует данный интерфейс
  • Self : объект должен представлять тот же класс или его производный класс. Может использоваться только внутри класса.
  • parent : объект должен представлять родительский класс данного класса. Может использоваться только внутри класса.

Типизация параметров функции

При типизации параметров тип указывается перед названием параметра:

function isPositive(int $number) < return $number >0; > $result1 = isPositive(25); // норм - 25 число $result2 = isPositive("25"); // норм - PHP может преобразовать значение в число $result3 = isPositive("-Youdontknowwhoiam"); // Ошибка TypeError

В данном случае параметр $number должен представлять тип int , то есть целое число. Поэтому при вызове функции мы должны передать в функцию целочисленное значение. Если будет передано значение другого типа, то PHP попытается преобразовать значение. В некоторых случаях такое преобразование можно завершится успешно:

В других случаях прееобразование может завершится неудачно, и программа завершит выполнение с ошибкой TypeError :

$result3 = isPositive("-Youdontknowwhoiam");
function sum(array $numbers, callable $condition) < $result = 0; foreach($numbers as $number)< if($condition($number)) < $result += $number; >> return $result; > $isPositive = function($n) < return $n >0;>; $myNumbers = [-2, -1, 0, 1, 2, 3, 4, 5]; $positiveSum = sum($myNumbers, $isPositive); echo $positiveSum; // 15

В данном случае параметры функции должный представлять массив и другую функцию (тип callable ). В качестве функции можно передать анонимную функцию.

Типизация возвращаемого значения

Для установки типа возвращаемого из функции значения после списка параметров указывается двоеточие : и после него тип данных:

function isPositive (int $number) : bool < return $number >0; > $result = isPositive(34);

В данном случае функция isPositive должна возвращать значение типа bool , то есть true или false .

Другой пример — возвращение функции:

function select($n): callable< switch($n)< case 1: return function($a, $b) ; case 2: return function($a, $b) ; case 3: return function($a, $b) ; default: return function($a, $b) ; > > $selection = select(2); echo $selection(4,5); // -1

Особо стоит отметить ключевое слово static , добавленное в PHP 8, которое применяется, если надо возвратить из метода класса объект этого же класса:

class Node < function generate() : static< return new Node(); >> $node1 = new Node(); $node2 = $node1->generate();

Типизация свойств

В качестве типа свойств может применяться любой тип кроме callable :

class Person < public $name; public int $age; >$tom = new Person(); $tom->name = "Tom"; $tom->age = 36; // корректное значение echo $tom->age; // 36 $tom->age = "36"; // корректное значение, так как PHP может преобразовать в число echo $tom->age; // 36 $tom->age = "thirty-eight"; // некорректное значение, возникнет ошибка TypeError echo $tom->age;

В данном случае явным образом определено, что свойство $age представляет именно тип int , то есть целое число. Соответственно этому свойству мы сможем присвоить только целое число.

Стоит учитывать, что свойство, для которого не указан тип данных, по умолчанию имеет значение null . Тогда как свойство, для которого указан тип, неинициализировано, то есть не имеет никакого конкретного значения.

Соответственно если нетипизированное свойство мы сможем использовать, то при попытке обратиться к типизированному, но неинициализиованному свойству программа завершит выполнение ошибкой:

$tom = new Person(); echo $tom->name; // норм - null echo $tom->age; // ошибка - свойство неинициализировано

Тип Union

В PHP 8 был добавлен тип union или объединение, который по сути представляет объединение типов, разделенных вертикальной чертой | . Например, мы хотим написать функцию сложения чисел, и чтобы в функцию можно было передавать только числа. Однако числа в PHP предствлены двумя типами — int и float . Чтобы не создавать по функции для каждого типа, применим объединения:

function sum(int|float $n1, int|float $n2,): int|float < return $n1 + $n2; >echo sum(4, 5); // 9 echo "
"; echo sum(2.5, 3.7); // 6.2

В данном случае мы говорим, что параметры $n1 и $n2 могут представлять как тип int , так и тип float . Аналогично возвращаемое значение также может представлять либо int , либо float .

Источник

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