V
V
Valery Ryaboshapko2014-02-19 20:02:56
PHP
Valery Ryaboshapko, 2014-02-19 20:02:56

How to restrict the type of parameters in a function?

In compiled languages ​​like Pascal or C, when describing a function, I can (and must) strictly specify the type of the input parameters. The maximum where I can turn around is to use function reloading, writing several times a function with the same name, but a different set of parameters.
In PHP, dynamic typing gives a lot of room for imagination, but this is a double-edged sword.
For example, I am writing a class and I want to pass a parameter of a complex structure to one of the methods, for example, a multidimensional associative array or an object. In principle, I can write a method that will assume that the correct parameter was passed to it, and work with it right away. I can even write a check for compliance with the structure (roughly speaking, ) and give an error in Run Time.isset($arrat['text_index'])
But can I force the interpreter to check the correctness of the passed parameter and give errors like these?

Parse error, unexpected T_STRING, expecting T_SOMETHING

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Litvinov, 2014-02-19
@valerium

You can do this by specifying the type of the parameter when defining the function

function example(array $hello){
return $hello;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question