Use start and end parameters without using the middle ones. PHP

Asked

Viewed 34 times

0

Good night!

Imagine that I have a Function with some parameters set as null:

public function Usuario($Nome = null, $Idade = null, $Sexo = null, $Email = null) {

    $this->Nome = (string) $Nome;
    $this->Idade = (int) $Idade;
    $this->Sexo = (string) $Sexo;
    $this->Email = (string) $Email;

}

Let’s assume I only want to use Name and Email, Sex and Age. How do I do this When I call the method?

  • I guess the way is: Usuario("nome", null, null, "email")

2 answers

2


According to the documentation of PHP:

"Note that using standard arguments, any pattern must come after the non-standard arguments: otherwise, things will not work as expected."

That is, the only way to do what you want to do is by passing the already null parameters:

Usuario("nome", null, null, "email");

0

You can pass the parameters through array, this facilitates, especially if the amount of parameters is large.

public function Usuario($dados = array()) {

  $this->Nome = isset($dados["nome"]) ? $dados["nome"] : null;
  $this->Idade = isset($dados["idade"]) ? $dados["idade"] : null;
  $this->Sexo = isset($dados["sexo"]) ? $dados["sexo"] : null;
  $this->Email = isset($dados["email"]) ? $dados["email"] : null;

}

// montando array
$dados = array();
$dados["nome"] = "João";
$dados["idade"] = "20";

// chamando função
Usuario($dados);

Browser other questions tagged

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