What is the syntax that comes before the variable name in function parameters?

Asked

Viewed 67 times

5

Reading the PHP documentation I came across the following example:

function bar(A $a = null, $b) {} // Ainda permitido
function bar(?A $a, $b) {}       // Recomendado

I did a little digging and figured out the function of ?, but what does the A being passed before the variable $a?

1 answer

4


In both cases it is the type of the variables being declared there, in the specific case of the example the variable is a parameter, then the variable will be typed, it should only be used with values of this type. There’s nothing going on there.

So $a must contain a value of type A, or like ?A that the kind will surely A, but may have a null value.

Obviously A is a bad name of type or anything else, since it does not say what it is, and precisely why the documentation is not good at it.

I even understand that the purpose of the documentation is only to show an aspect of it, but it is strange to talk about "recommended" and in one variable it is used in the recommended way, but another uses the way that is no longer recommended, that is, it is declared without the hinttype.

PHP decided that it no longer wants to be a language of script and now wants to compete with Java, C#, Swift, Kotlin, C++, etc. Of course this is not possible without breaking compatibility with everything that has already been done the way script, not allowing it to be a good transition and obliging to accept what is now considered the wrong way to do, so it depends on the discipline of the programmer to do in the most appropriate way.

  • Very strange indeed. When I researched the ?, I saw that he came before variables and not the type, so I figured I was missing something. Thank you very much friend!

  • 3

    Noting @FURIUS the documentation says that this "declaration method" means that the value can be of the specified or null "type", ie 2:bar(null, "aaaaa") as @Maniero mentioned this is a bad name of type (forces you to understand an acronym that has nothing to do..)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.