PHP’de otomatik olarak class import işlemleri için autoload işlemlerini kullanabilirsiniz. Genel kullanıma değineceğimiz bir örnekle başlayalım.
Öncelikle functions.php isimli bir dosya oluşturup aşağıdaki gibi düzenleyin.
<?php // functions.php function load_model($class_name) { $path_to_file = 'models/' . $class_name . '.php'; if (file_exists($path_to_file)) { require $path_to_file; } } spl_autoload_register('load_model'); // otomatik olarak bağlar. Class kullanımlarında bu metodu çağırmaya gerek yoktur.
Ana dosyanız ise oluşturulan dosyayı import edip işlemlerinizi yapabilirsiniz.
<?php require 'functions.php'; $contact = new Contact('john.doe@example.com');
Birden fazla fonksiyon için autoload işlemi yapabilirsiniz;
<?php spl_autoload_register('meyveleriYukle'); $elma = new Elma(); $armut = new Armut(); $karpuz = new Karpuz(); spl_autoload_register('sebzeleriYukle'); $domates = new Domates(); $patates = new Patates(); $salata = new Salata();
Birden fazla dizinde çalışma yapıyorsanız; örneğin servisler ve modeller isimli iki dizinde autoload işlemi de şu şekildedir;
Örnek dizinler;
├── functions.php
├── index.php
├── models
│ └── Contact.php
└── services
└── Email.php
<?php // Email.php class Email { public static function send($contact) { return 'Sending an email to ' . $contact->getEmail(); } } // functions.php function load_model($class_name) { $path_to_file = 'models/' . $class_name . '.php'; if (file_exists($path_to_file)) { require $path_to_file; } } function load_service($service_name) { $path_to_file = 'services/' . $service_name . '.php'; if (file_exists($path_to_file)) { require $path_to_file; } } spl_autoload_register('load_model'); spl_autoload_register('load_service'); // From the index.php, you can use the Contact and Email classes as follows: require 'functions.php'; $contact = new Contact('john.doe@example.com'); echo Email::send($contact); // Output: // Sending an email to john.doe@example.com
İlk Yorumu Siz Yapın