Приглашаем посетить
PHP (php.find-info.ru)

Section 12.13.  Getters That Double as Setters

Previous
Table of Contents
Next

12.13. Getters That Double as Setters

Another alternative to the pattern of creating two different methods for getting and setting a parameter is to create one method that notes whether or not it gets any additional arguments. If the arguments are absent, it's a get operation; if the arguments are present, it's a set operation. A simple version looks like:

sub color {
  my $self = shift;
  if (@_) {              # are there any more parameters?
    # yes, it's a setter:
    $self->{Color} = shift;
  } else {
    # no, it's a getter:
    $self->{Color};
  }
}

Now we can say:

my $tv_horse = Horse->named('Mr. Ed');
$tv_horse->color('black-and-white');
print $tv_horse->name, ' is colored ', $tv_horse->color, "\n";

The presence of the parameter in the second line denotes that we are setting the color, while its absence in the third line indicates a getter.

This strategy is attractive because of its simplicity, but it also has disadvantages. It complicates the actions of the getter, which is called frequently. It also makes it difficult to search through our code to find the setters of a particular parameter, which are often more important than the getters. We've been burned in the past when a setter became a getter because another function returned more parameters than expected after an upgrade.


Previous
Table of Contents
Next