How to automatically load function in PHP - php

I use this code to load classes
function __autoload($className)
{
$files = dirname(__FILE__).'/public/class/'.$className.'.php';
if(file_exists($files))
{
include_once($files);
}
}
does anyone know how to retrieve the function automatically, too? Thank you.

Autoloader function registered spl_autoload_register() can be used to load classes, but not functions. Wrap your functions in class or classes to utilize autoloading, i.e.
class Utils {
static function foo() {
..
}
}
then call it static way:
Utils::foo();
and you can have it autoloaded when needed. See more infromation on autoloading in PHP manual.

Yes, you can automatically load classes using the autoload feature, but no, you can't do the same for functions.

Related

Use PHP method from different class/file

If I want to add methods to my file from other classes or a script not using OOP should I include() the file or extend it in my class?
Include and create a new instance of this class.
For OOP classes you would have to decide if the object needs to be an instance. If its just a utility of functions you could use static methods like below:
class EmailFilter
{
public function clean($email)
{
...
}
public static function filter($email) {
....
}
}
You would then require the code and use
Static
EmailFilter::filter($email);
Object
$filter = new EmailFilter();
foreach ($emails as $email) {
$filter->clean($email);
}
if its non-oop functions you can include/require the code and use the functions as needed within your code.

PHP newbie - PHP Classes autoloading and Securing

I am interested in learning autoloading, but new to PHP.
I am reading the book "PHP in Action" which writes the autoload method like
function __autoload($className) {
include_once __autoloadFilename($className);
}
function __autoloadFilename($className) {
return str_replace('_','/',$className).".php";
}
I want to pack these methods in a class. will it be better to pack them in an abstract class?
Or in normal class and including it in index.php?
How effeciently I can use the autoloading feature?
Thanks
Securing an autoloader, ensure:
That the file you try to load is actually a file. include is pretty much like eval. For example disallow url inclusion via the php configuration.
That the classname is actually a syntactically correct classname. Could be helpful to secure things ;)
You can also white-list namespaces and/or classnames that are appropriate for your concrete autoloader.
Create a class as an autoloader, you must not take the static way, you can just assign any callback with spl_autoload_register, so you can register multiple autoloaders.
Some quickly written autoloader class stub:
class MyAutoloader
{
public function __construct()
{
$this->register();
}
public function register()
{
spl_autoload_register(array($this,'autoload'));
}
public function autoload($classname)
{
if ($this->isInvalidClassName($classname)) return;
$file = $this->getFileForClassName($classname);
if ($this->isInalidFile($file)) return;
require $file; // bail out fatally.
}
...
}
$myAutoloader = new MyAutoloader();
It's up to you. I use a dedicated class called Loader with a method called load(), which I activate with:
spl_autoload_register( 'Utility_Loader::load' );

PHP Including 2 files using same function names give redeclare error?

i'm having trouble with a redeclare error. I can't find a fix for it yet, but basically:
I have 2 files that are modules and they use the same function names like install(), uninstall() etc etc which are used by the system.
When I include both the files at the same time for gathering data, I get a redeclare error. I want it so that I can include both and when the next file is loaded, it just rewrites over the previous function.
Or is there a way I can unset or clear the function? I've tried include, require, require_once etc... No work :(
In PHP it is not possible to overwrite a function that you have previously defined.
So the modules stand in each others way and one module prevents the other from working.
Actually Modules need to make use of the same named functions while they must be able to co-exist next to each other.
That can be done by moving the modules code into classes of their own. One module is one class then.
You can then define an interface with the functions your module classes must provide. As Modules therefore must have a streamlined interface - each module has a install() and uninstall() function for example - just define an object interface at first specifying those needed module functions:
module_definitions.php
interface Module {
public function install();
public function uninstall();
}
mod_Module1.php:
class Module1 implements Module {
public function install() {...}
public function uninstall() {...}
}
mod_Module2.php:
class Module2 implements Module {
public function install() {...}
public function uninstall() {...}
}
After doing so, whenever one of your routines needs to deal with any module, you can make that function require a module:
function module_install(Module $module) {
$module->install();
}
This function will only accept an existing module as a parameter. So you can not use your standard require/include for this but modules need to be instantiated prior use. You can put that into a module loader function as well:
function module_require($moduleName) {
$class = $moduleName;
if (!class_exists($class) {
$file = sprintf('mod_%s.php', $moduleName);
require $file;
if (!class_exists($class)) {
throw new DomainException(sprintf('Invalid Module File %s for Module %s.', $file, $moduleName));
}
}
}
How to access the modules functions then?
The only thing left is now to access the actual module.
You could the create a global array variable containing all modules:
// Define existing modules
$modules = array('Module1', 'Module2');
// Require the modules
array_map('module_require', $modules);
// instantiate each module:
$moduleInstances = array_map(function($module){return new $module;}, $modules);
// map modules name (key) to it's module instance:
$modules = array_combine($modules, $moduleInstances);
// access module by name:
$modules['Module1]->install();
However this has some problems. All modules need to be loaded at once for example, but you might not need to use all modules. Or imagine you would overwrite the global $modules array, all modules would be lost.
To prevent all that and allow more control and easier access to the modules, this can be put into a class of it's own that will take care of all the details. Like a register that knows which modules are loaded or not, registers them as needed.
For the following I assume a module can only exists once. If an object can only exist once this is often called a Singleton. So we'll wrap the management of loading and providing the module by it's name into a class of it's own that deals with the details:
class Modules {
private $modules = array();
private static $instance;
// singleton implementation for Modules manager
private static function getInstance() {
if (null === Modules::$instance) {
Modules::$instance = new Modules;
}
return Modules::$instance;
}
// singleton-like implementation for each Module
public function get($moduleName) {
if (!isset($this->modules[$moduleName]) {
module_require($moduleName);
$newModule = new $moduleName();
if (! $newModule instanceof Module) {
throw new DomainException(sprintf('Not a Module: %s', $moduleName));
}
$this->modules[$moduleName] = $newModule;
}
return $this->modules[$moduleName];
}
// get a module by name
public static function get($moduleName) {
return Modules::getInstance()->get($moduleName);
}
}
Put this class into module_definitions.php as well, which should be always included in your application.
So whenever you need to access a module you can do now by using the static get function with the name of the module:
Modules::get('Module1')->install();
Modules::get('Module2')->install();
No. You have a application design problem.
Rename the second function and call it on the locations you want the second to be used.
You cannot have two functions with the same name in the same scope.
If you have php5.3 or above, namespaces can be the answer: each plugin has its own, so the functions became
\plugin1\install()
\plugin2\install()
et cetera.
You may also wish to create unique classes inside these include files, then have them extend a generic class and use that generic class as a type to anchor to when you want to call up these functions at a higher level. You could also have one overload the other and then when you execute a method in one, it could be passed right on to the next.
Theoretically if you wrap the functions of each file in a separate class then you can call them both without problems. You don't even need to really worry about class state if you call them statically.
You cant use two time the same function name in the same namespace.
You should rename your second function or use namespaces like "Maerlyn" suggest
This problem can be solved by namespaces or/and static class.
Easiest way is to wrap these functions in class with static methods.
After that you'll be able not only to include them both, but also to use autoload-functions and forget about 'include'.
class Class1
{
public static function install()
{}
}
class Class2
{
public static function install()
{}
}
More about namespaces and autoload

Dynamically building/loading a class library in PHP

I am fairly new to OO programming...
I am building what will eventually turn out to be a large library of classes to be used throughout my site. Clearly, loading the entire library on every page is a waste of time and energy...
So what I would like to do is require a single "config" php class file on each page, and be able to "call" or "load" other classes as needed - thus extending my class according to my needs.
From what I know, I can't use a function in the config class to simply include() other files, because of scope issues.
What are my options? How do developers usually handle this problem, and what is the most stable?
You can use __autoload() or create an Object Factory that will load the files required when you need them.
As an aside, if you're having scope issues with your library files, you should probably refactor your layout. Most libraries are sets of classes that can be instantiated in any scope.
The following is an example very basic object factory.
class ObjectFactory {
protected $LibraryPath;
function __construct($LibraryPath) {
$this->LibraryPath = $LibraryPath;
}
public function NewObject($Name, $Parameters = array()) {
if (!class_exists($Name) && !$this->LoadClass($Name))
die('Library File `'.$this->LibraryPath.'/'.$Name.'.Class.php` not found.');
return new $Name($this, $Parameters);
}
public function LoadClass($Name) {
$File = $this->LibraryPath.'/'.$Name.'.Class.php'; // Make your own structure.
if (file_exists($File))
return include($File);
else return false;
}
}
// All of your library files should have access to the factory
class LibraryFile {
protected $Factory;
function __construct(&$Factory, $Parameters) {
$this->Factory = $Factory;
}
}
Sound like you want autoload and spl_autoload_register if you are using classes from 3rd party libraries.

using require inside a class

i want to make a "loader class" that will require selected files.
so i just can call eg. loader::load('systemLibraries, 'applicationLibraries').
so inside this load() method i will use require. but i have tried this and it seems that the files required can't be used outside the class.
how can i make it globally accessed?
This should work fine:
class Loader{
function load($class_name)
{
require($class_name ".php");
}
}
Loader::load("MyClass");
$class = new MyClass;
Given that MyClass is in "MyClass.php"
This on the other hand, won't work
class Loader{
function load($class_name)
{
require($class_name ".php");
$class = new $class_name;
}
}
Loader::load("MyClass");
$class->doSomething();
If include.php looks like this
$var = "Hi";
You can't do this:
Loader::load("include");
echo $var;
As there are scope issues.
You are going to need to give us more information on exactly what you are trying to access.
Yes, as Chacha pointed out, make sure that you create the instance of the classes outside of your loader class. And since you have used the term system libraries which are usually always needed by the system, you can use the __autoload magic function to included them all automatically for you.

Categories