Answer the question
In order to leave comments, you need to log in
Why are there so many methods in a class?
Hello! Explain plz why do such methods in classes?
class Person {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function getTitle() {
return $this->getName()." the person";
}
public function sayHello() {
echo "Hello, I'm ".$this->getTitle()."<br/>";
}
}
$geekObj = new Person("Ludwig");
$geekObj->sayHello();
Answer the question
In order to leave comments, you need to log in
Because in the future you will be able to painlessly add logic to the method (getting a value from the config, from the database, calling an authorization check, etc., for a setter - data validation). If you have a blank field, then you will have to change the client code, and this violates the abstraction.
Rule of thumb: The class API should only be accessible through methods or properties (which is essentially syntactic sugar over methods), and fields should only be private/protected.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question