开发者

php terminology: difference between getters and public methods?

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

What's the difference between a getter method and a public method i开发者_运维知识库n 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!


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->getName(); // 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->getName(), "\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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜