Skip to content
PHP Logo

How can the Factory design pattern be implemented to create and execute objects with dynamic method calls in PHP?

When using the Factory design pattern in PHP to create and execute objects with dynamic method calls, we can define a Factory class that instantiates different types of objects based on certain criteria. We can then use this Factory class to create objects and call methods dynamically based on user input or other conditions.

php
<?php

// Define a Factory class
class ObjectFactory {
    public static function createObject($type) {
        switch ($type) {
            case 'TypeA':
                return new TypeA();
            case 'TypeB':
                return new TypeB();
            default:
                return null;
        }
    }
}

// Define example classes with dynamic methods
class TypeA {
    public function dynamicMethod() {
        echo "TypeA dynamic method called\n";
    }
}

class TypeB {
    public function dynamicMethod() {
        echo "TypeB dynamic method called\n";
    }
}

// Create and execute objects with dynamic method calls using the Factory
$objectType = 'TypeA';
$object = ObjectFactory::createObject($objectType);
$object->dynamicMethod();

$objectType = 'TypeB';
$object = ObjectFactory::createObject($objectType);
$object->dynamicMethod();

?>