Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shahr's avatar
Level 10

Validation OOP PHP

How to change this code t PHP OOP Validation?

<?php
$errors = [];
function request($field) {
    return isset($_REQUEST[$field]) && $_REQUEST[$field] != '' ? trim($_REQUEST[$field]) : null;
}
function hasError($field) {
    global $errors;
    return isset($errors[$field]);
}
function getError($field) {
    global $errors;
    return hasError($field) ? $errors[$field] : '';
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = request('name');
    $email = request('email');
    $password = request('password');
    $password_confirm = request('password_confirm');
    $image = request('image');
    if (is_null($name)) {
        $errors['name'] = 'The name can not null.';
    }
    if (is_null($email)) {
        $errors['email'] = 'The email can not null.';
    }

    if (is_null($password)) {
        $errors['password'] = 'The password can not null.';
    } elseif (strlen($password) < 6) {
        $errors['password'] = 'The password must be < 6.';
    }
    if (!is_null($name) && !is_null($email) && !is_null($password) && isset($_FILES['image']) && $_FILES['image']['error'] != UPLOAD_ERR_NO_FILE) {
        echo 'Save user data in database.';
    }
}
?>
0 likes
1 reply
Ben Taylor's avatar

Why don't you take a dive into the Laravel source code and see how it's done there?

Please or to participate in this conversation.