Php function argument types

PHP Functions

PHP has more than 1000 built-in functions, and in addition you can create your own custom functions.

PHP Built-in Functions

PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a specific task.

Please check out our PHP reference for a complete overview of the PHP built-in functions.

PHP User Defined Functions

Besides the built-in PHP functions, it is possible to create your own functions.

  • A function is a block of statements that can be used repeatedly in a program.
  • A function will not execute automatically when a page loads.
  • A function will be executed by a call to the function.

Create a User Defined Function in PHP

A user-defined function declaration starts with the word function :

Syntax

Note: A function name must start with a letter or an underscore. Function names are NOT case-sensitive.

Tip: Give the function a name that reflects what the function does!

In the example below, we create a function named «writeMsg()». The opening curly brace ( < ) indicates the beginning of the function code, and the closing curly brace ( >) indicates the end of the function. The function outputs «Hello world!». To call the function, just write its name followed by brackets ():

Читайте также:  Свойство background size css

Example

writeMsg(); // call the function
?>

PHP Function Arguments

Information can be passed to functions through arguments. An argument is just like a variable.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument ($fname). When the familyName() function is called, we also pass along a name (e.g. Jani), and the name is used inside the function, which outputs several different first names, but an equal last name:

Example

familyName(«Jani»);
familyName(«Hege»);
familyName(«Stale»);
familyName(«Kai Jim»);
familyName(«Borge»);
?>

The following example has a function with two arguments ($fname and $year):

Example

function familyName($fname, $year) echo «$fname Refsnes. Born in $year
«;
>

familyName(«Hege», «1975»);
familyName(«Stale», «1978»);
familyName(«Kai Jim», «1983»);
?>

PHP is a Loosely Typed Language

In the example above, notice that we did not have to tell PHP which data type the variable is.

PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.

In PHP 7, type declarations were added. This gives us an option to specify the expected data type when declaring a function, and by adding the strict declaration, it will throw a «Fatal Error» if the data type mismatches.

In the following example we try to send both a number and a string to the function without using strict :

Example

function addNumbers(int $a, int $b) return $a + $b;
>
echo addNumbers(5, «5 days»);
// since strict is NOT enabled «5 days» is changed to int(5), and it will return 10
?>

To specify strict we need to set declare(strict_types=1); . This must be on the very first line of the PHP file.

In the following example we try to send both a number and a string to the function, but here we have added the strict declaration:

Example

function addNumbers(int $a, int $b) return $a + $b;
>
echo addNumbers(5, «5 days»);
// since strict is enabled and «5 days» is not an integer, an error will be thrown
?>

The strict declaration forces things to be used in the intended way.

PHP Default Argument Value

The following example shows how to use a default parameter. If we call the function setHeight() without arguments it takes the default value as argument:

Example

setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>

PHP Functions — Returning values

To let a function return a value, use the return statement:

Example

PHP Return Type Declarations

PHP 7 also supports Type Declarations for the return statement. Like with the type declaration for function arguments, by enabling the strict requirement, it will throw a «Fatal Error» on a type mismatch.

To declare a type for the function return, add a colon ( : ) and the type right before the opening curly ( < )bracket when declaring the function.

In the following example we specify the return type for the function:

Example

You can specify a different return type, than the argument types, but make sure the return is the correct type:

Example

Passing Arguments by Reference

In PHP, arguments are usually passed by value, which means that a copy of the value is used in the function and the variable that was passed into the function cannot be changed.

When a function argument is passed by reference, changes to the argument also change the variable that was passed in. To turn a function argument into a reference, the & operator is used:

Example

Use a pass-by-reference argument to update a variable:

Источник

Php function argument types

To experiment on performance of pass-by-reference and pass-by-value, I used this script. Conclusions are below.

#!/usr/bin/php
function sum ( $array , $max ) < //For Reference, use: "&$array"
$sum = 0 ;
for ( $i = 0 ; $i < 2 ; $i ++)#$array[$i]++; //Uncomment this line to modify the array within the function.
$sum += $array [ $i ];
>
return ( $sum );
>

$max = 1E7 //10 M data points.
$data = range ( 0 , $max , 1 );

$start = microtime ( true );
for ( $x = 0 ; $x < 100 ; $x ++)$sum = sum ( $data , $max );
>
$end = microtime ( true );
echo «Time: » .( $end — $start ). » s\n» ;

/* Run times:
# PASS BY MODIFIED? Time
— ——- ——— —-
1 value no 56 us
2 reference no 58 us

3 valuue yes 129 s
4 reference yes 66 us

1. PHP is already smart about zero-copy / copy-on-write. A function call does NOT copy the data unless it needs to; the data is
only copied on write. That’s why #1 and #2 take similar times, whereas #3 takes 2 million times longer than #4.
[You never need to use &$array to ask the compiler to do a zero-copy optimisation; it can work that out for itself.]

2. You do use &$array to tell the compiler «it is OK for the function to over-write my argument in place, I don’t need the original
any more.» This can make a huge difference to performance when we have large amounts of memory to copy.
(This is the only way it is done in C, arrays are always passed as pointers)

3. The other use of & is as a way to specify where data should be *returned*. (e.g. as used by exec() ).
(This is a C-like way of passing pointers for outputs, whereas PHP functions normally return complex types, or multiple answers
in an array)

5. Sometimes, pass by reference could be at the choice of the caller, NOT the function definitition. PHP doesn’t allow it, but it
would be meaningful for the caller to decide to pass data in as a reference. i.e. «I’m done with the variable, it’s OK to stomp
on it in memory».
*/
?>

Источник

Php function argument 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.

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 7 и 8

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

Типизация в PHP

В языке PHP динамическая типизация. Это значит, что при инициализации переменной ей нельзя назначить тип. Тип переменной выставиться динамически в зависимости от значения (или результат выполнения выражения), которое ей присваивается. Он может меняться в процессе выполнения скрипта. Продемонстрирую на примере:

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

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

В последних версиях PHP появился возможность указывать типы для аргументов функций и возвращаемого ею значения. Рассмотрим эти возможности на примере:

 // Вызываем функцию myTestOperation(123, 'test', [4, 5, 6]);

Код содержит функцию с 3 аргументами различных типов. Типы указываются перед именем аргумента, а тип возращаемого значения после двоеточия.

Обратите внимание на строку «declare(strict_types=1);» Она включает строгую типизацию. Например, если при строгой типизации мы передадим в первый аргумент функции строку вместо числа, то получим ошибку:

TypeError: Argument 1 passed to myTestOperation() must be of the type int, string given

Если удалить строчку declare(strict_types=1) , PHP попытается преобразовать переданную строку в число. Если преобразовать невозможно, PHP выбросит исключение TypeError.

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

  • int — целочисленный тип;
  • float — числа с плавающей точкой (десятичная дробь);
  • string — строка;
  • array — массив;
  • callable — callback-функция;
  • имя класса — в качестве аргумента должен передаваться экземпляр класса;
  • интерфейс — в качестве аргумента должен передаваться класс, имплементирующий (реализующий) данный интерфейс.

Null и void в сигнатуре функции

В случае, если функция или метод класса не возвращают значение, после двоеточия пишется ключевое слово void.

В случае, если какие-то из аргументов функции мы захотим сделать необязательными, на нужно добавить знак ? перед именем типа. Это правило работает и для возвращаемого значения. Например, для аргумента ?int $myVar можно передать значение либо null, либо целое число. Чтобы явно не передавать null в качестве значения необязательного аргумента, обычно в сигнатуре присваивают значение по умолчанию, как показано в следующем примере:

function myTestOperation(int $firstParam, ?string $secondParam = null, ?array $thirdParam = null): ?float < var_dump($firstParam); // выведет int(6) var_dump($secondParam); // выведет NULL var_dump($thirdParam); // выведет NULL return null; // Можно венруть null, так как в сигнатуре ?float (либо десятичная дробь, либо null) >// Вызываем функцию // Явно передаем null во 2 и 3 аргументы myTestOperation(6, null, null); // Вызываем еще раз // При этом не передаем необязательные аргуметы, так как в сигнатуре присвоены дефолтные значения // При этом результат выполнения будет идентичен myTestOperation(6);

Преимущества указания типов в PHP

Использование типов и строгой типизации дает на следующие преимущества:

  • снижает риск ошибок, связанными с типами;
  • выполняет функцию документации — то есть мы видим: какого типа данные нужно передавать в качестве аргумента в функцию;
  • заставляет вас правильно проектировать функцию, не позволяя принимать аргументы и возвращать значения разных типов.

Типизация свойств объекта в PHP 7.4

В PHP версии 7.4 появилась возможность указывать типы в классах.

Источник

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