[Solved] How can I use OOP PHP in this contact form? [closed]


The first thing I want to say is that it doesn’t make sense to ask how to apply OOP to a form; what I guess you need is an example of a script PHP that uses OOP to handle the data from the form.

Hoping you are just making you first steps, I wanna help you for this time.

To begin, you can declare the class you need in a ContactForm.php file; this class should have a property for any field you have in the contact form, all protected and with their own setter and getter method in respect of “Encapsulation” concept:

<?php

class ContactForm {
    protected $name;
    protected $email;
    protected $subject;
    protected $message;

    public function setName($name){
        $this->name = $name;
    }
    public function getName(){
        return $this->name;
    }
    // do the same for email, subject and message fields
}

Once you have this class you can write a script contact.php that includes the ContactForm.php class and use it to work with data from the POST HTTP:

<?php

require 'ContactForm.php'; // assuming they are in the same folder

$contactForm = new ContactForm();
$contactForm->setName($_POST['name']);
// do the same for email, subject and message fields

// after all set, you can use getters if you need to work with the data in the class, example:
$contactForm->getName();

A few consideration:

  • Check this link if you don’t know what Encapsulation is
  • This is a very generic example with the name only, but following the comments you can add all fields you need
  • I didn’t consider any security check: you should validate data from $_POST before using it in order to prevent bad data and attacks

Hope I was clear, if not let me know.

2

solved How can I use OOP PHP in this contact form? [closed]