Skip to content

Define PHP classes dynamically with variable name

How to Define PHP classes dynamically with variable name is one question I have received lately. Although not practical, it is possible.

If you need to dynamically define classes, then use Anonymous Classes, otherwise you should be giving your classes fixed names, not based on random variable values.

$myClass = 'Person';

$$myClass = new class() {
    function function_one() {
        echo "LOL";
    }
};

$$myClass->function_one();

If you need any help, don’t hesitate to contact us.