PHP design patterns

Help me understand the patterns php. There is a basic abstract class that defines the methods of the object's behavior. For example, class Field.

abstract class Field
{
    static function getInstance($instance)
    {
        return new $instance;
    }
    abstract function createField();
}

In the script, you need to create an object that will inherit from this base class and set its behavior, depending on the heir.

class TextField extends Field
{
    protected function createField()
    {
         return 'textfield';
    }
}

class SelectField extends Field
{
    protected function createField()
    {
         return 'selectfield';
    }
}

At the same time, I need to somehow store the value of the currently created object in the base class. Something like a singleton needs to be created so that I can then initialize Field::createInstance('SelectField') at any time to know which object is currently being used. Can you tell me what is the best pattern to use, or can you give me an idea of how to implement it?

Author: Aegis, 2013-08-29

1 answers

<?php 
    abstract class Field
    {
        static $childType = null;

        function __construct($type) {
            if (!is_null($type)) {
                self::$childType = $type;
            }
        }

        static function getInstance($instance)
        {
            return new $instance;
        }
        abstract protected function createField();
    }

    class TextField extends Field
    {
        function __construct() {
            parent::__construct(__CLASS__);
        }

        protected function createField()
        {
            return 'textfield';
        }
    }

    class SelectField extends Field
    {
        function __construct() {
            parent::__construct(__CLASS__);
        }

        protected function createField()
        {
            return 'selectfield';
        }
    }

    $TextField = new TextField();
    echo Field::$childType . "<br/>\n";

    $SelectField = new SelectField();
    echo Field::$childType . "<br/>\n";
?>
 1
Author: Steve, 2015-12-18 18:08:58