Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Object-Oriented PHP Basics Building the Recipe Access Modifiers

Kevin Howbrook
Kevin Howbrook
5,003 Points

Getters and Setters vs Magic methods?

Just a general 'wonder', if the standard is to use 'set' or 'get' in the method name. Is this different to using the php magic method _get and _set?

Alena Holligan
Alena Holligan
Treehouse Teacher

Yes, naming getters and setters with 'get' and 'set' respectively is a standard across many programming languages.

Using the magic methods __get and __set is called 'overloading'. You could use them if you wanted to allow public or private variables to be accessed 'directly'. Maybe have the same controls put in place for all properties.

class MyOverload
{
    private $one;
    protected $two;
    public $three;

    public function __set($name, $value) {
        $this->$name = strtoupper($value);
    }
}

$me = new MyOverload();
$me->one = "one";
$me->two = "two";
$me->three = "three";
var_dump($me);

Both the private and protected properties will use the magic __set method, but since you can already access the public property directly, it does NOT use the the magic method. Results:

object(MyOverload)#1 (3) {                                                                                    
  ["one":"MyOverload":private]=>                                                                              
  string(3) "ONE"                                                                                       
  ["two":protected]=>                                                                                         
  string(3) "TWO"                                                                                       
  ["three"]=>                                                                                                 
  string(5) "three"                                                                                           
}  

You could also check for certain property names within the __set method as well, if you wanted to control things that way.

class MyOverload
{
    private $one;
    protected $two;
    public $three;

    public function __set($name, $value) {
        switch ($name) {
            case 'one':
                $this->$name = strtoupper($value);
                break;
            default:
                return 'cannot set ' . $name . ' property';
        }
    }
}