1

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?

3 Answers3

1

You need to use static class for it http://php.net/manual/en/language.oop5.static.php

class Validator
{ 
    static function foo() 
   {
      echo 'bar'; 
   }
}

Use it by calling :

Validator::foo();

To call it 'Anywhere' you may have to include the file of your class or use an autoload.

Gectou4
  • 219
  • 1
  • 5
0

You cannot store in constants non-scalar values, but you can use Singleton pattern.

<?php
class Singleton
{
    /**
     * @var Singleton The reference to *Singleton* instance of this class
     */
    private static $validator;

    /**
     * Returns the *Singleton* instance of this class.
     *
     * @return Singleton The *Singleton* instance.
     */
    public static function getValidator()
    {
        if (null === static::$validator) {
            static::$validator = new Validator();
        }

        return static::$validator;
    }

    /**
     * Protected constructor to prevent creating a new instance of the
     * *Singleton* via the `new` operator from outside of this class.
     */
    protected function __construct()
    {
    }

    /**
     * Private clone method to prevent cloning of the instance of the
     * *Singleton* instance.
     *
     * @return void
     */
    private function __clone()
    {
    }

    /**
     * Private unserialize method to prevent unserializing of the *Singleton*
     * instance.
     *
     * @return void
     */
    private function __wakeup()
    {
    }
} 
Dmytrechko
  • 598
  • 3
  • 11
  • Not sure who gave the downvote - this is the right answer. This is exactly what singletons are for. The most ubiquitous use of a "constant" (which it's not, really) object is a database connection. You don't want to connect to your database in a dozen different classes, so you keep a singleton that remembers your DB connection. Caching is common too. – Josh from Qaribou Oct 11 '16 at 14:39
  • First of all, this is not the singleton pattern as it is known in OOP (for me that's still the one described by the GoF). I would rather call this an instance class or some trivial application of the Factory pattern. Also, the singleton pattern is often considered an [anti-pattern](http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons). Also in this case, I might need multiple validator instances (contact-info, flight-info, complaints, etc.). Summarised: the factory pattern might have lead to a better answer... – Mr Tsjolder from codidact Oct 11 '16 at 14:44
  • @JoshfromQaribou I am the one to blame for the down-vote. My argumentation can be found in my previous comment. Also: you're right, a database is one of the few examples where singletons make sense. – Mr Tsjolder from codidact Oct 11 '16 at 14:48
0

The answer that should have come is actually that it does not make sense to have some global constant validator for use on multiple pages. After some more looking around, I found out that

  1. php constants are compile-time constants and thus unsuited for storing objects.
  2. static variables have the lifetime of a request and thus cannot be used across multiple pages.

Therefore, it is necessary to initialise a validator for every request. If validator initialisation would be immensely expensive to create, it might be an option to serialise the object to some file and deserialise it to get it back. However, I think that this suggestion is (or should be) practically irrelevant.

If, on the other hand, the same validator could be used multiple times during one single request, it might make sense to consider a static variable with accompanying method to access it as already suggested in the question.

Apologies if my question was not perfectly clear