How to use class variable as default value in php functions?

Asked

Viewed 448 times

4

class Teste(){
  public variavel;
  public variavela;

  function teste($parametro=$this->variavel, $parametro2->$this->variavela){
    // code
  }
}

Returns me the following error:

Parse error: syntax error, Unexpected '$this' (T_VARIABLE)

  • There’s no point in doing that. Since you can take the value of the class variable at any time within the function I don’t understand what the need to pass the value in the parameter...

2 answers

10

What you are trying to do is not valid in PHP.

According to the manual:

The default value [of a function parameter] needs to be a constant expression, not (for example) a variable, a class member or a function call.

An alternative with a similar operation:

class Teste(){
  public $variavel;
  public $variavela;

  function teste($parametro = null, $parametro2 = null){
    $parametro = $parametro ? $parametro : $this->variavel;
    $parametro2 = $parametro2 ? $parametro2 : $this->variavela
  }
}

In this example, if any of the parameters is not passed in the function call, the default value will be the class member value.

  • Your reply also helped me, however I must assume that the way as bfavaretto presented is more 'dry'. Thank you.

  • 2

    @Lucasanjos the answer the bfavaretto solves the problem but it has nothing more DRY than this. This is 100% DRY.

5


You cannot do this, the standard values of parameters need to be constant. The most PHP allows is to use class constants, with static reference:

class Teste {
  const VARIAVEL = 10;
  const VARIAVELA = 20;

  function __construct($parametro=self::VARIAVEL, $parametro2=self::VARIAVELA){
    echo "$parametro - $parametro2";
  }
}

$t = new Teste();

http://ideone.com/l1NX5y

Although in this case it’s worth putting the literal values directly in the function signature, isn’t it? It’s cleaner:

class Teste {   
  function __construct($parametro=10, $parametro2=20){
    echo "$parametro - $parametro2";
  }
}

$t = new Teste();

If you need a solution with dynamic values, assign the values within the function itself, as @Andréribeiro suggested in his answer.

  • Thank you for sending the source of the reply, help me with my future research. This solves my problem.

  • Okay, but I think André Ribeiro’s answer is the most recommended way. What I posted is more like...

Browser other questions tagged

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