What are some best practices for handling variables passed through URLs in PHP classes?

When handling variables passed through URLs in PHP classes, it is important to sanitize and validate the input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. One way to achieve this is by using PHP's filter_input() function to retrieve and filter the input data from the URL parameters.

class User {
    private $userId;

    public function __construct() {
        $this->userId = filter_input(INPUT_GET, 'user_id', FILTER_SANITIZE_NUMBER_INT);
    }

    public function getUserId() {
        return $this->userId;
    }
}

$user = new User();
echo $user->getUserId();