Php terminology: difference between getters and public methods?

My question is more about terminology and then about technical capabilities (or is it?).

What is the difference between a getter method and a public method in a class? Are they the same or are there differences between them?

I ask because I'm trying to learn the best coding methods, and this area seems gray to me. I commented on my code and noticed that I have a large section called "Getters" and another large section called "Public Methods", and then I was like ... "what is diff ?!".

Thanks!

+4
source share
3 answers

Simply put, getter in PHP is just a method that allows other parts of your code to access a specific property of the class .

For instance:

<?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 ?> 

Perhaps the method need not be designed solely to return a property; you can create other methods so that your class can do funky things .

To extend the example above, 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 creating the object outside 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 . This is normal since the $name property is in the same class. The purpose of the getter (and its corresponding installer, if any) is to provide other parts of your code with access to this property.

+5
source

Getters are public methods that return the value of a private variable. Similarly, setters are publicly available methods that allow you to modify or "set" a private variable.

+1
source

Public methods can be updated outside the class, and the class does not need to know about it.

A public receiver or setter gives you more flexibility - i.e. when we try to read $obj->$property , the variable may not be ready. However, if we use $obj->getSomething() , we can do something with this variable to make it ready,

The difference is that public recipients usually return a private variable. This means that the only way to get the state of a property from an object is to get it using a method that may or may not do unnecessary things.

0
source

All Articles