Skip to content
PHP Logo

How can the design of the code in the provided example be improved for better object-oriented programming practices in PHP?

The design of the code can be improved by encapsulating the properties of the `Person` class and providing getter and setter methods to access and modify them. This follows the principle of encapsulation in object-oriented programming. Additionally, we can use constructor injection to set the initial values of the properties when creating a new instance of the `Person` class.

php
class Person {
    private $name;
    private $age;

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

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

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

    public function getAge() {
        return $this->age;
    }

    public function setAge($age) {
        $this->age = $age;
    }
}

$person = new Person("John", 30);
echo $person->getName() . " is " . $person->getAge() . " years old.";