Example of Nested Class Structure in PHP

Example of Nested Class Structure in PHP


Example of Nested Class Structure in PHP

In order to write more organized code in PHP, sometimes we need to create nested classes, but since PHP isn’t as robust as C# in terms of class structures, we might have difficulty creating them. 
Here is an example of a nested class structure in PHP that you can use in such cases.

Class Structure Example

Since PHP does not support nested class structures, to create one, we need to use a function and return a class from it.

<?php
    class Config {
        // Database connection settings
        public static function database(): object
        {
            return new class {

                // Mongo db connection settings
                public static function mongo(): object
                {
                    return new class {
                        public static string $host = "localhost";
                        public static int $port = 27017;
                        public static string $username = "mongo_username";
                        public static string $password = "mongo_password";
                        public static string $database = "mongo_database";
                    };
                }

                // Mysql db connection settings
                public static function mysql(): object
                {
                    return new class {
                        public static string $host = "localhost";
                        public static int $port = 3306;
                        public static string $username = "mysql_username";
                        public static string $password = "mysql_password";
                        public static string $database = "mysql_database";
                    };
                }
            };
        }

        // Email connection settings
        public static function email(): object
        {
            return new class {
                public static string $host = "smtp.domain.com";
                public static int $port = 465;
                public static string $email = "email_account@domain.com";
                public static string $username = "email_account@domain.com";
                public static string $password = "email_password";
            };
        }
    }

Usage Example

To use the nested class we prepared above, you need to use the following method.

    
$mysqlConfig = Config::database()->mysql();
echo $mysqlConfig::$host;

You can use the class you wrote with the usage example above.