What is the difference between these parameters (array) in these methods?

Asked

Viewed 552 times

12

I see it a lot in methods

class Exemplo
{
    public function exemplo1(array $parameters = array())
    {
    }

    public function exemplo2(array $parameters)
    {
    }

    public function exemplo3($parameters = array())
    {
    }
}

It means that $parameters is a array, but what’s the difference between these implementations?

7 answers

13


Two important concepts you need to understand are the hinting type and default value of the parameter.

The hinting type obliges which argument has passed a specific type (in case a array).

From PHP 7 we can do hinting type of primitive types (int, string, float).

Before PHP 7 or hinting type is limited to Objects, Interfaces, arrays and closures.

Now the default value of the parameter, is the value that the parameter will take case nay nothing is passed to that parameter. Understand as a parameter optional.

Taking your examples, you would then have:

// Um método que obriga que o argumento seja um array 
// mas aceita uma chamada sem parâmetros:
public function exemplo1(array $parameters = array()){ }

$obj->exemplo1();

// Obriga que o argumento seja um array, e que o parâmetro seja passado: 
public function exemplo2(array $parameters){ }

$obj->exemplo2(array('id' => 1));

// Se nada for passado como argumento, assumirá o valor de um array vazio, 
// mas te permite passar outros tipos como argumento
public function exemplo3($parameters = array()){ }

$obj->exemplo3("Eu nao sou um array, mas tudo bem!");

When passing a default value that does not satisfy the hinting type, an error will be returned:

// Type hinting de array e valor padrão string
public function test(array $teste = "array")

PHP Fatal error: Default value for Parameters with array type hint can only be an array or NULL

  • Work gmsantos, by your attention! I understood perfectly...

11

The first two are explicitly indicating that the parameter should receive one array. The latter no, a value of any kind can be passed. This is called hinting type in PHP.

The first and last initialize the parameter with a array emptiness if no value is passed to it. The priority will be of the argument passed if it exists.

  • Thanks bigown, for your attention!

7

This first method defines $parameters must be an array if a value other than that is generated an error, if no argument is passed parameters will be treated as an empty array.

public function exemplo1(array $parameters = array())

Example:

$e = new Exemplo();
$e->exemplo1(1);

Error generated:

Catchable fatal error: Argument 1 passed to Example::exemplo1() must be of the type array, integer Given, called

Requires that parameters is an array, otherwise it generates the same error quoted above, and its default value is NULL and not an empty array like exemplo1().

public function exemplo2(array $parameters)

Defines that if no argument is passed $parameters will be an empty array, this method accepts other values such as a string or integer.

public function exemplo3($parameters = array())

The type defined on the left side of the parameter is called hinting type, This ensures that the defined type must be respected if something different comes an error is released. But it is not possible to type parametres with primitive types(int, float, Sting), int or string. Resources and Traits. Usually the name of a class or interface is placed.

  • Thanks rray, for your attention! I understood perfectly!

7

This is my understanding

 public function exemplo2(array $parameters)

The function this forcing that the programmer passes a array.


public function exemplo3($parameters = array())

The function is setting the value pattern as array, but the programmer can pass anything.


 public function exemplo1(array $parameters = array())

The function only accepted values of the type array and the completion and optional, if the programmer does not pass will use the value pattern array()

  • Thank you Icaro Martins for your attention!

3

In function exemplo1 the array serves to indicate that the parameter $parameters must be an array. If the function is called with a parameter of another type PHP will generate a warning (Warning) stating that the type passed is incorrect.

The part = array() serves to initialize the value of the parameter, which makes it optional when calling the function.

  • Thank you André Ribeiro for your attention!

3

Just to complement, as already said in the other answers:

//O primeiro parâmetro deve ser array ou vazio (caso vazio assume `array()`)
public function exemplo1(array $parameters = array())

//O primeiro parâmetro deve ser um array e não pode ser vazio
public function exemplo2(array $parameters)

//O primeiro parâmetro deve ser de qualquer tipo, se vazio assume `array()`
public function exemplo3($parameters = array())

Now the additional ones, the parameters using type hinting are now supported in this order:

PHP 5.0.0

  • Class/interface: The parameter The parameter must be an instance of a given name of a class or interface.

  • self: The parameter must be an instance of the same class as the method is defined in. This can only be used in class and instance methods.

PHP 5.1.0

  • array The parameter of being an array

PHP 5.4.0

  • callable The parameter must a function or method or something equivalent to the same that can be called so $param(); and equals to is_callabe();

PHP 7.0.0

The PHP7 (released on 3/Dec/2015) started to support several types and PHP7 started to be called Type declarations and started to generate a Typeerror Exception when declared a parameter of a different type.

currently it is in the version 7.0.3 (released on 4/Feb/2016), It is strongly recommended not to use 7.0.0, 7.0.1 and 7.0.2.

  • bool the must parameter if of the boolean type (true or false).
  • float the parameter must be a floating point number (1.1, 2.5, 3.8, etc)
  • int the parameter must be of the integer type 1, 2, 3 for example.
  • string the parameter must be of the string type.

Strict types (Strict)

PHP7 also supported "Strict mode" for type declaration, for example:

<?php
declare(strict_types=1);

function sum(int $a, int $b) {
    return $a + $b;
}

var_dump(sum(1, 2));
var_dump(sum(1.5, 2.5));

The result will be this error:

int(3)

Fatal error: Uncaught TypeError: Argument 1 passed to sum() must be of the type integer, float given, called in - on line 9 and defined in -:4
Stack trace:
#0 -(9): sum(1.5, 2.5)
#1 {main}
  thrown in - on line 4

Type return

Also supported in PHP7 the type return, for example:

<?php
function sum($a, $b): float {
    return $a + $b;
}

var_dump(sum(1, 2));

This also supports the strict

0

About each method

Basically what changes is just the signature of the method, they could be doing the same thing.

Method exemplo1: an array type value is expected, moreover, this method is receiving a default value that is an empty array, which makes the parameter optional.

Method exemplo2: in this method an array type value is expected. The parameter is not optional in this case.

Method exemplo3: the method accepts any type of value, as no type hinting has been defined. In addition, the parameter in question is optional and is receiving an array as default value, however it is not restricted to receiving arrays only.

Browser other questions tagged

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