Using one method as Getter and Setter

Instead of writing two methods  in your class with the single purpose of getting or setting a value to a class member, you can simply create one method to do both.

<?php
class foo()
{
    protected
        $var;
    public function bar($string = null)
    {
        if($string === null) {
            return $this->var;
        }
        $this->var = $string;
        return true;
    }
}

$example = new foo();
$example->bar(); // Returns null, no value assigned
$example->bar('Q`pla'); // Returns true, assigns value
$example->bar(); // Returns Q`pla

If no argument is passed to the method, you simply return the assigned value.  If an argument is passed, then you assign the passed value to the class member.

This way your class can remain small(er) and easier to maintain.

Leave a Reply

Your email address will not be published. Required fields are marked *