When working on a PHP project that takes advantage of the OOP paradigm with PHP's __autoload()
function, which of the following is considered the best practice for managing stand-alone functions:
(Examples provided are simplified for the sake of brevity)
tl;dr: How is stand-alone function loading commonly handled:
- pseudo-autoloading (via
__callStatic
magic for example) [Option 1]- abstract helper class grouped static methods [Option 2]
- an alternative
Also note, I've posted a related question regarding a parameter/reference issue with option 1, which can be found here: __callStatic(), call_user_func_array(), references, and PHP 5.3.1
Given in index.php
:
function __autoload($class){
require $class . '.class.php';
}
Option 1; An abstract Core
class (or Library
, or whatever) that "autoloads" functions:
## Core.class.php
abstract class Core{
public static function __callStatic($function, $arguments){
if(!function_exists($function)){
require $function . '.function.php';
}
return call_user_func_array($function, $arguments);
}
}
## SayHello.function.php
function sayHello(){
echo 'Hello';
}
## SayGoodbye.function.php
function sayGoodbye(){
echo 'Goodbye';
}
## index.php
Core::sayHello(); // Hello
Core::sayGoodbye(); // Goodbye
Option 2; Grouping related functions into abstract "helper" classes to be called statically:
## SayStuff.class.php
abstract class SayStuff{
public static function sayHello(){
echo 'Hello';
}
public static function sayGoodbye(){
echo 'Goodbye';
}
}
## index.php
SayStuff::sayHello(); // Hello
SayStuff::sayGoodbye(); // Goodbye