The PHP getter/setter

Monday, March 12th, 2012

Perl has a neat way to define both a getter and a setter in the same class method. The basic definition goes a little like this:

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

PHP can do something similar with a structure that matches quite cleanly to the code above. The example below is taken from our upcoming stand-alone form library.

public function name() {
    if ( func_num_args() ) {
        $this->_name = func_get_arg( 0 );
        return $this;
    } else {
        return $this->_name;

In the example above, passing a value to the method named name() will set the value and return the object (to allow chaining). If the method is called without a parameter, it return the current value of the object’s name.

This structure is preferable to the magic methods __set and __get for its clarity.

Leave a Reply