Vlada Katlinskaya
Vlada Katlinskaya

Reputation: 1033

Method definition: how can I use class property as a default function parameter?

First I tried to declare the following class:

class MyClass{
  public $min;
  public $max;
  function my_func($min=$this->min,$max=$this->max){
  }
}

PHP throws syntax error, unexpected T_VARIABLE error. So I need to do something like this:

class MyClass{
  public $min;
  public $max;
  function my_func($min=NULL,$max=NULL){
    if(!isset($min)) $min = $this->min;
    if(!isset($max)) $max = $this->max;
  }
}

Which trows no errors (I didn't tested this code but I think it should work).

However this approach has several drawbacks:

  1. I can not transfer NULL as a value to the function as default values will be used instead.

  2. This is lengthy

Is there any better solution?

EDIT 1

As proposed by @nickb I can use constants:

class MyClass{
    const MIN = 0;
    const MAX = 10;

    function my_func($min = MyClass::MIN, $max = MyClass::MAX) {
    }
}

This is a good solution except a case the $min and $max intended to change from time to time:

$a = new MyClass();
$min = 0;
$max = 10;
$b = new MyClass();
$a->MyFunc(1,2);
$b->MyFunc();

Unfortunately this is my case :(

It is probably a forced scenario and I shouldn't built such 'flexibility' to the class but this is exactly what I planned to do. I should add a note: I'm really a novice at OOP.

Upvotes: 1

Views: 33

Answers (1)

nickb
nickb

Reputation: 59699

You could use constants:

class MyClass{
    const MIN = 0;
    const MAX = 10;

    function my_func($min = MyClass::MIN, $max = MyClass::MAX) {
    }
}

You just have to keep in mind that the default values must be constant expressions. From the manual:

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

Upvotes: 1

Related Questions