views:

63

answers:

3

My question is more about terminology then technicalities (or is it?).

What's the difference between a getter method and a public method in a class? Are they one in the same or is there a distinction between them?

I ask because I'm trying to learn best coding practices and this area seems grey to me. I was commenting my code out and noticed I had a big section called "Getters" and another big section called "Public Methods" and then I was like... "what's the diff?!".

Thanks!

+1  A: 

Getters are public methods that return the value of a private variable. In a similar vein, setters are public methods that allow modification or "setting" of a private variable.

dave
To extend upon this: getters and setters are used to accomplish `data encapsulation`.
erisco
A: 

Public methods can be updated from outside the class, and the class doesn't necessarily have to know about it.

A public getter or setter gives you more flexibility - i.e. when we try and read $obj->$property, the variable might not be ready. However, if we use $obj->getSomething() we can do anything to that variable, to make it ready,

The difference is that public getters generally return a private variable. This means the only way to get the state of a property from the object is to get it via a method, which may or may not do extra things.

alex
+3  A: 

In simple terms, a getter in PHP is simply a method that allows other parts of your code to access a certain class property.

For example:

<?php

class Person {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    // Getter
    public function getName() {
        return $this->name;
    }
}

$bob = new Person('Bob');
echo $bob->name; // Bob

?>

A method may not necessarily be designed to just return a property though; you can create other methods so that your class can do funky things.

To expand on the above example, let's give the Person class a method called say(), and give it a function/method parameter representing what to say:

    public function say($what) {
        printf('%s says "%s"', $this->name, $what);
    }

And call it after we create an object out of the class:

$bob = new Person('Bob');
echo $bob->name, "\n"; // Bob
$bob->say('Hello!'); // Bob says "Hello!"

Notice that inside the say() method I refer to $this->name. It's OK, since the $name property is found in the same class. The purpose of a getter (and its corresponding setter if any) is to allow other parts of your code to access this property.

BoltClock
+1 for bolding "do funky things" :-D
erisco
This makes perfect sense. Thanks for the excellent explanation.
ctown4life