I wrote a class to validate form input which knows about certain fields (keys in the input-array) and allows to specify rules for it. This would allow to create a validator that takes care of contact data, e.g. with fields "title"
, "name"
and "email"
.
The idea of my design was that this validator could then be reused for multiple forms that are spread around on the website. After all, many of these forms might require to fill out some contact data. The only thing I did not think of is that php does not allow to initialise constants or static fields with objects.
I hoped to use my validator by specifying it in some file utils.php
as
const CONTACT_VALID = new Validator(...);
such that I could just require "utils.php"
to access this constant without it being initialised every time. This obviously does not work and also with static variables this does not work.
I also thought about something like
static CONTACT_VALID = NULL;
static function get_contact_valid() {
if (is_null(CONTACT_VALID))
CONTACT_VALID = new Validator();
return CONTACT_VALID;
}
but I am not completely sure whether this would have the desired effect as I am relatively new to php (and web technology in general).
So my question: Is there any possibility to have an object such that I can use it anywhere on the website without having to initialise it again and again?