In what ways can object-oriented programming principles be applied to PHP form generation to enhance code reusability and maintainability?

Object-oriented programming principles can be applied to PHP form generation by creating reusable form classes that encapsulate form elements and functionality. By creating form classes, code reusability is increased as forms can be easily reused across different parts of the application. Additionally, maintaining forms becomes easier as changes can be made in a centralized location within the form class.

<?php

class Form {
    private $fields = [];

    public function addField($name, $type, $label) {
        $this->fields[] = [
            'name' => $name,
            'type' => $type,
            'label' => $label
        ];
    }

    public function render() {
        $form = '<form>';
        foreach ($this->fields as $field) {
            $form .= '<label>' . $field['label'] . '</label>';
            $form .= '<input type="' . $field['type'] . '" name="' . $field['name'] . '">';
        }
        $form .= '</form>';

        return $form;
    }
}

$form = new Form();
$form->addField('username', 'text', 'Username');
$form->addField('password', 'password', 'Password');

echo $form->render();

?>