Php İç İçe Class Yapısı Örneği

Php İç İçe Class Yapısı Örneği


Php İç İçe Class Yapısı Örneği

Php ile daha düzenli kod yazmak için zaman zaman iç içe sınıflar oluşturmamız gerekebiliyor, bu gibi durumlarda php, c# kadar iyi bir sınıf yapısına sahip olmadığı için oluşturmakda zorluk çekebiliyoruz. 
İşte bu gibi durumlarda kullanabileceğiniz php ile iç içe sınıf yapısı örnepi.

Class Yapısı Örneği

Php iç içe sınıf yapısını desteklemediği için, iç içe sınıf yapısı oluşturmak için fonksiyo kullanıp bundan bir sınıf döndürmemiz gerekiyor.

<?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";
            };
        }
    }

Kullanım Örneği

Yukarıda hazırladığımız iç içe sınıfı kullanmak için aşağıdaki yöntemi kullanmanız gerekiyor.

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

Yazdığınız sınıfı yukarıdaki örneği kullanım örneği ile kullanabilirsiniz.