A
A
Alexey2017-01-16 11:30:35
PHP
Alexey, 2017-01-16 11:30:35

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();

it turns out we call the getTitle() -> getName() method, which ultimately prints out just the $name variable.
Why not just refer to it already in the sayHello() method?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Fat Lorrie, 2017-01-16
@dzheka3d

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 question

Ask a Question

731 491 924 answers to any question