There is like a million Template Engine for PHP (Blade, Twig, Smarty, Mustache, ...), and i just hate the idea of creating a new syntax and compiler to write PHP inside HTML! I think it's just not smart (but this isn't what i am here to discuss :) ), what is wrong with writing PHP+HTML the usual way - not for logic - you know, all the variables and loops and defines you wanna use without this {{% %}} or that {:: ::} ! At least for performance sake!
Now, i am using Laravel these days , and it's awesome; it offers (besides Blade and any other 3rd party engine) a plain PHP templates system that uses ob_start/include/ob_get_clean and eval. I was very happy to know that i can avoid learning a new syntax to write PHP inside HTML.
Here is what i am suggesting; what about instead of using ob_* functions with include, we use Closures ? Here is a simple class i put together just to make a point:
class Templates{
static public $templates = array();
static public function create($name, $code){
self::$templates[$name] = $code;
}
static public function run($name, $data){
if(!isset(self::$templates[$name]) || !is_callable(self::$templates[$name])) return false;
return call_user_func(self::$templates[$name], $data);
}
}
And here is how to use it:
Templates::create('test', function($data){
return 'Hi '.$data['name'].' ! ';
});
for($i =0; $i < 10; $i++){
print Templates::run('test', array('name' => 'Jhon'));
}
I think this way is much better, since i wont need to do any output buffering or use eval. And to "separate concerns" here, we can put the Templates::create code in a separate file to keep things clean, in fact this way things can become more simple and elegant; we can make another method to load the template file:
static public function load($name){
self::create($name, include($name.'.php'));
}
And the content of the template file will be as simple as this:
return function($data){
return 'Hi '.$data['name'].' ! ';
};
What do you think of this ? Is there any problems with the approach or the performance of such use of Closures ?
I do not think there are any problems besides that if you put all closure functions into array, that would possibly mean that functions are kinda doing basically the same stuff.
What I mean by this:
In your example you have your functions accepting only 1 parameter. So, not to create a mess all functions you create would accept the same set of parameters and return the same type of data.
However when declared apart, functions may be supposed to do something different and unique.
Why such a solution is suitable: when using some engines, there may be a lot of different functions declared already. To resolve the conflict, they can be "hidden" inside arrays.
Also, some people even say that anonymous functions can be generally better in case of performance. But we have to test that first: to call a function you:
Call a static function run
Check a function for existence
Check a function for callability
And then use call_user_func which returns the return of your function. So, 3x return.
Update
My recomendations for you code:
Make all possible checks only when creating a function. That will greatly buff performance.
static public function create($name, $code){
if (!isset(self::$templates[$name])){
if (is_callable($code)){
self::$templates[$name] = $code ;
} else {
//func is not callable, Throw an exception.
}
} else {
//function already exists. Throw an exception.
}
}
That way you just can have 2x increase in performance:
static public function run($name, $data){
if (isset(self::$templates[$name])){
self::$templates[$name]($data); //Just make a straight call
} else {
//throw new Exception(0, "The func is not defined") ;
}
}
Related
In JavaScript nested functions are very useful: closures, private methods and what have you..
What are nested PHP functions for? Does anyone use them and what for?
Here's a small investigation I did
<?php
function outer( $msg ) {
function inner( $msg ) {
echo 'inner: '.$msg.' ';
}
echo 'outer: '.$msg.' ';
inner( $msg );
}
inner( 'test1' ); // Fatal error: Call to undefined function inner()
outer( 'test2' ); // outer: test2 inner: test2
inner( 'test3' ); // inner: test3
outer( 'test4' ); // Fatal error: Cannot redeclare inner()
If you are using PHP 5.3 you can get more JavaScript-like behaviour with an anonymous function:
<?php
function outer() {
$inner=function() {
echo "test\n";
};
$inner();
}
outer();
outer();
inner(); //PHP Fatal error: Call to undefined function inner()
$inner(); //PHP Fatal error: Function name must be a string
?>
Output:
test
test
There is none basically. I've always treated this as a side effect of the parser.
Eran Galperin is mistaken in thinking that these functions are somehow private. They are simply undeclared until outer() is run. They are also not privately scoped; they do pollute the global scope, albeit delayed. And as a callback, the outer callback could still only be called once. I still don't see how it's helpful to apply it on an array, which very likely calls the alias more than once.
The only 'real world' example I could dig up is this, which can only run once, and could be rewritten cleaner, IMO.
The only use I can think of, is for modules to call a [name]_include method, which sets several nested methods in the global space, combined with
if (!function_exists ('somefunc')) {
function somefunc() { }
}
checks.
PHP's OOP would obviously be a better choice :)
[Rewritten according to the comment by #PierredeLESPINAY.]
It's not just a side-effect at all, but actually a very useful feature for dynamically modifying the logic of your program. It's from the procedural PHP days, but can come in handy with OO architectures too, if you want to provide alternative implementations for certain standalone functions in the most straightforward way possible. (While OO is the better choice most of the time, it's an option, not a mandate, and some simple tasks don't need the extra cruft.)
For example, if you dynamically/conditionally load plugins from your framework, and want to make the life of the plugin authors super easy, you can provide default implementations for some critical functions the plugin didn't override:
<?php // Some framework module
function provide_defaults()
{
// Make sure a critical function exists:
if (!function_exists("tedious_plugin_callback"))
{
function tedious_plugin_callback()
{
// Complex code no plugin author ever bothers to customize... ;)
}
}
}
Functions defined within functions I can't see much use for but conditionally defined functions I can. For example:
if ($language == 'en') {
function cmp($a, $b) { /* sort by English word order */ }
} else if ($language == 'de') {
function cmp($a, $b) { /* sort by German word order; yes it's different */ }
} // etc
And then all your code needs to do is use the 'cmp' function in things like usort() calls so you don't litter language checks all over your code. Now I haven't done this but I can see arguments for doing it.
All the above being said, one might simply create a nested function to replace some localized, repetitive code within a function (that will only be used inside the parent function). An anonymous function is a perfect example of this.
Some might say just create private methods (or smaller code blocks) in a class, but that is muddying the waters when an ultra-specific task (which is exclusive to the parent) needs to be modularized, but not necessarily available to the rest of a class. The good news is if it turns out that you do need that function somewhere else, the fix is rather elementary (move the definition to a more central location).
Generally speaking, using JavaScript as the standard by which to evaluate other C based programming languages is a bad idea. JavaScript is definitely its own animal when compared to PHP, Python, Perl, C, C++, and Java. Of course, there are lots of general similarities, but the nitty, gritty details (reference JavaScript: The Definitive Guide, 6th Edition, Chapters 1-12), when paid attention to, make core JavaScript unique, beautiful, different, simple, and complex all at the same time. That's my two cents.
Just to be clear, I'm not saying nested functions are private. Just that nesting can help avoid clutter when something trivial needs to be modularized (and is only needed by the parent function).
All of my php is OO, but I do see a use for nested functions, particularly when your function is recursive and not necessarily an object. That is to say, it does not get called outside of the function it is nested in, but is recursive and subsequently needs to be a function.
There's little point in making a new method for the express use of a single other method. To me that's clumsy code and sort-of not the point of OO. If you're never going to call that function anywhere else, nest it.
In webservice calling we found it a much lower overhead (memory and speed) dynamically including in a nested fashion, individual functions over libraries full of 1000s of functions. The typical call stack might be between 5-10 calls deep only requiring linking a dozen 1-2kb files dynamically was better than including megabytes. This was done just by creating a small util function wrapping requires. The included functions become nested within the functions above the call stack. Consider it in contrast to classes full of 100s of functions that weren't required upon every webservice call but could also have used the inbuilt lazy loading features of php.
if you are in php 7 then see this:
This implementation will give you a clear idea about nested function.
Suppose we have three functions(too(), boo() and zoo()) nested in function foo().
boo() and zoo() have same named nested function xoo(). Now in this code I have commented out the rules of nested functions clearly.
function foo(){
echo 'foo() is called'.'<br>';
function too(){
echo 'foo()->too() is called'.'<br>';
}
function boo(){
echo 'foo()->boo() is called'.'<br>';
function xoo(){
echo 'foo()->boo()->xoo() is called'.'<br>';
}
function moo(){
echo 'foo()->boo()->moo() is called'.'<br>';
}
}
function zoo(){
echo 'foo()->zoo() is called'.'<br>';
function xoo(){ //same name as used in boo()->xoo();
echo 'zoo()->xoo() is called'.'<br>';
}
#we can use same name for nested function more than once
#but we can not call more than one of the parent function
}
}
/****************************************************************
* TO CALL A INNER FUNCTION YOU MUST CALL OUTER FUNCTIONS FIRST *
****************************************************************/
#xoo();//error: as we have to declare foo() first as xoo() is nested in foo()
function test1(){
echo '<b>test1:</b><br>';
foo(); //call foo()
too();
boo();
too(); // we can can a function twice
moo(); // moo() can be called as we have already called boo() and foo()
xoo(); // xoo() can be called as we have already called boo() and foo()
#zoo(); re-declaration error
//we cannont call zoo() because we have already called boo() and both of them have same named nested function xoo()
}
function test2(){
echo '<b>test2:</b><br>';
foo(); //call foo()
too();
#moo();
//we can not call moo() as the parent function boo() is not yet called
zoo();
xoo();
#boo(); re-declaration error
//we cannont call boo() because we have already called zoo() and both of them have same named nested function xoo()
}
Now if we call test1() the output will be this:
test1:
foo() is called
foo()->too() is called
foo()->boo() is called
foo()->too() is called
foo()->boo()->moo() is called
foo()->boo()->xoo() is called
if we call test2() the output will be this:
test2:
foo() is called
foo()->too() is called
foo()->zoo() is called
zoo()->xoo() is called
But we cannot call both text1() and test2() at same time to avoid re-declaration error
For those that suggest that there is no practical use of nested functions. Yes they have use and this is an example.
Imagine that I have a file called my_file.php which is used to get an ajax result out of. But what if there are times that you don't want to get the result through ajax but you want to include it twice in the same page without conflicts?
Lets say ajax file my_file.php :
<?php
// my_file.php used for ajax
$ajax_json_in = 10;
function calculations($a, $b)
{ $result = $a + $b;
return $result;
}
$new_result = $ajax_json_in * calculations(1, 2);
$ajax_json_out = $new_result;
?>
Below example includes the above file twice without conflict. You may not want to ajax call it, because there are cases that you need to include it straight in the HTML.
<?php
// include the above file my_file.php instead of ajaxing it
function result1
{
$ajax_json_in = 20;
include("my_file.php");
return $ajax_json_out;
}
function result2
{
$ajax_json_in = 20;
include("my_file.php");
return $ajax_json_out;
}
?>
Including the file makes the file's functions nested. The file is used both for ajax calls and inline includes !!!
So there is use in real life of nested functions.
Have a nice day.
I know this is an old post but fwiw I use nested functions to give a neat and tidy approach to a recursive call when I only need the functionality locally - e.g. for building hierarchical objects etc (obviously you need to be careful the parent function is only called once):
function main() {
// Some code
function addChildren ($parentVar) {
// Do something
if ($needsGrandChildren) addChildren ($childVar);
}
addChildren ($mainVar); // This call must be below nested func
// Some more code
}
A point of note in php compared with JS for instance is that the call to the nested function needs to be made after, i.e. below, the function declaration (compared with JS where the function call can be anywhere within the parent function
I have only really used this characteristic when it was useful to execute a small recursive function inside a primary, more categorical function, but didn't want to move it to a different file because it was fundamental to the behavior of a primary process. I realize there are other "best practice" ways of doing this, but I want to make sure my devs see that function every time they look at my parser, it's likely what they should modify anyway...
Nested functions are useful in Memoization (caching function results to improve performance).
<?php
function foo($arg1, $arg2) {
$cacheKey = "foo($arg1, $arg2)";
if (! getCachedValue($cacheKey)) {
function _foo($arg1, $arg2) {
// whatever
return $result;
}
$result = _foo($arg1, $arg2);
setCachedValue($cacheKey, $result);
}
return getCachedValue($cacheKey);
}
?>
Nested functions are useful if you want the nested function to utilize a variable that was declared within the parent function.
<?php
ParentFunc();
function ParentFunc()
{
$var = 5;
function NestedFunc()
{
global $var;
$var = $var + 5;
return $var;
};
echo NestedFunc()."<br>";
echo NestedFunc()."<br>";
echo NestedFunc()."<br>";
}
?>
I am building a PHP MVC framework like Ruby on Rails but with PHP for learning. The link just in case you want to see it is https://github.com/carlinoo/vinum
I was trying to see the source code of CakePHP as it is very similar to mine. When in aa action in a controller, after the logic of that action/method, it calls the view, a different file that has access to those variables. I cant seem to understand how that works.
How does it call the view after the logic is finished? In CakePHP there’s something called autoRender that if set to true, it renders the appropriate view. How can you do that without calling a function to render the view?
Also, I have a variable scope problem. Let me explain:
function func1() {
$var = 1;
render();
}
function render() {
require_once(‘file.php’);
}
// This is file.php
<?php
echo $var;
?>
$var one does not exist because of the scope, and i don’t want to declare the variables as global. How do big PHP Frameworks do this? And how does the autoRender actually work? Thank you
This is the "easy" way
function func1() {
$var = 1;
render(‘file.php’, get_defined_vars());
}
function render($file, $vars = []) {
extract($vars);
require $file; //pass the filename in for reuse
}
But it's really messy, and prone to variable name collisions.
This function returns a multidimensional array containing a list of all defined variables, be them environment, server or user-defined variables, within the scope that get_defined_vars() is called.
http://php.net/manual/en/function.get-defined-vars.php
Import variables from an array into the current symbol table.
http://php.net/manual/en/function.extract.php
I would manually build an array of variables, pass that to render($vars) and then use extract().
function func1() {
$vars = ['var1' => 1];
render(‘file.php’, $vars);
}
Also I would use require instead of require_once otherwise if you need to render the same template multiple times it wont work, think like in the case of a post or something you can loop on and call render multiple times. For example
you may have a "controller" named posts.php
render('header.php');
render('menu.php');
foreach($posts as $post){
render('post.php', $post);
}
render('footer.php');
The main Idea behind a template is to eliminate structural PHP mixed into the HTML. So you would want, smaller chunks of HTML that you can reuse multiple times. And mostly keep it to echoing variables in the tempate/view
Lastly, I would take what I put above as "theoretical" code, I can't really test this very well, but that's the basic concept.
UPDATE
Here is a quick Psudo-ish Code example of what CakePHP does ( obviously its way more complex then i can do in an answer on here ).
Its mainly the difference between using procedural and object oriented coding.
class Controller{
protected $data;
public function index(){
$this->color = 'pink';
$this->render('view.php');
}
///magic method
public function __set( $key, $value){
$this->data[$key] = $value;
}
/*
you can do the same thing with a normal method
public function set( $key, $value){
$this->data[$key] = $value;
}
but instead of doign $this->color = 'pink';
you would do $this->set('color', 'pink');
*/
public function render($file){
/*
obviously I can easily access $this->data['color']
from within the scope of the same class.
*/
extract($this->data);
include $file;
/*
or any number of other things
like
$contents = file_get_contents($file);
foreach( $this->data as $key => $value )
$contents = str_replace('{'.$key.'}', value , $contents);
echo $contents;
for tags like {color} etc.
*/
}
}
Right here is every method they are using.
https://api.cakephp.org/3.5/class-Cake.Controller.Controller.html
And here is the source code for their controller,
https://api.cakephp.org/3.5/source-class-Cake.Controller.Controller.html#583-622
Honestly I wouldn't recommend using the magic metods like __set __get etc. because it Makes the code
harder to read
harder to maintain
more prone to error
less efficient, performance wise.
For example
$this->set('data', 'foo');
Is safe, but using
$this->data = 'foo';
Will wipe out that data array property, because in my example the data gets put into a class property named data as an array, so calling $this->data = foo; accesses the already existing property and overwrites it. Which then means you have to do all kinds of checks and other things to make sure nothing gets overwritten, and anytime you add any properties you have to deal with that kind of stuff. And if you miss something you may not find it for months and then one day, you set data in a controller and it all falls apart.
For reference.
http://php.net/manual/en/language.oop5.magic.php
Anyway
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I am learning Classes and OOP and PDO and all that stuff ( I know legacy php, so, can write php 4.x scripts with messy code ^^ ).
So, started to transform over my base template system to the new code
so far so good, sessions and PDO are in classes , pagination system is in a class, users are in a class (basicaly everything).
Here's my question.
I use 2 functions to do a single thing
first function is to get the user rights and it looks like this
function u()
{
if ($_SESSION['loggedin'] == 1)
{
return true;
}
else
{
return false;
}
}
As you can see, it just return true or false based on session (code contains more but is for admin/staff ).
Should I also convert this to a class ? or is it useless ? and leave it as a function ?
Then my second function is to get some arrays ( used for group system)
function arr($string, $separator = ',')
{
//Explode on comma
$vals = explode($separator, $string);
//Trim whitespace
foreach($vals as $key => $val) {
$vals[$key] = trim($val);
}
//Return empty array if no items found
//http://php.net/manual/en/function.explode.php#114273
return array_diff($vals, array(""));
}
As this function is only used for the group update and to get info from what groups users are in is it in a function
So my question,
as far as i understand OOP does it mean that you write code to make things 'easier', so should I also make a class of those functions to make things easier or is it useless as it makes it harder ?
if (u())
{code code};
if (a());
{admin code}
vs
$u = new User;
if $u->rank(user){
code code
}
if $u->rank(admin){
admin code
}
Base code can be found here
it is to give a idea what I am rewriting to pdo.
Should i rewrite a simple function to a class?
Will this make your code maintenance easier?
Is this function occuring on more than one place in your project?
I can't give you an absolute answer, however generating an Object Class in PHP for a static simple function is overkill. It means you need to write more code, and your PHP processor has to do several magnitudes more work for the same - simple - outcome.
If your function occurs just once in your project then NO, you do not need to classify it in any way. This just adds overhead.
But, if you are using this function across multiple scripts and especially if there is a reasonable expectation that this function might need editing/extending in the future, then following Don't Repeat Yourself programming means you could put this function into a Static Class.
In the context of this question I will say more about Static Classes below but other options to remove repetition could be having functions in an include file at the top of your script, this essentially does the same thing as a Static class.
Follow DRY and you can happily copy/paste your function into a Static Class and call that class as required.
Static Classes are not instantiated, and can be used as containers for abstract functions such as the one you are describing, which don't fit neatly elsewhere.
however, there is no conclusive answer without us knowing what you're expecting to do with your project, are you maintaining and developing this or just updating a project without adding new functionality?
There seems a large minority of people obsessive that everything needs to be in a class, regardless of efficiency. Resist this temptation to wrap everything in classes, unless:
Does it make your data management easier to modularise?
Does it reduce/remove code repetition?
Does it make your code easier for you to understand?
Static Class Example:
class StaticClass {
public static function u() {
return $_SESSION['loggedin'] == 1;
}
}
Usage:
StaticClass::u(); ///returns boolean.
To be honest your function is so simple that in this specific instance you might as well just code the if statement directly:
if(u()){
// runs if u comparison returns true
}
becomes:
if($_SESSION['loggedin'] == 1){
// runs the same comparison as u() but avoids the
//function/class overheads
}
One day, suppose you decide that you wish to handle both session and token based authentication.
interface AuthInterface
{
public function isAuthenticated(string $credentials): bool;
}
class SessionAuth implements AuthInterface
{
public function isAuthenticated(string $user)
{
return $_SESSION['loggedin'] == 1;
}
}
class TokenAuth implements AuthInterface
{
public function isAuthenticated(string $token)
{
// validate token and return true / false
}
}
So in above example, using classes is very handy. You can now switch out your implementations super easy - and your code should still work.
Writing classes and programming to an interface - enables you to depend on abstractions, not on concretions. It should make your life easier.
If you have a few functions that are like helpers - e.g a custom sorting function - then go ahead and keep as a function. No point going overboard.
I think you should be consistent in what you do, but if a function is really just something like
function u()
{
if ($_SESSION['loggedin'] == 1)
{
return true;
}
else
{
return false;
}
}
or if you make it short:
function(u) {
return $_SESSION['loggedin'] == 1;
}
There is no reason to create a class for a one-liner. Also some inprovements for your arr() function: If you want to apply a callback to all Elements of an array, use array_map()
function arr($string, $separator = ',')
{
//Explode on comma
$vals = explode($separator, $string);
//Trim whitespace
$vals = array_map("trim", $vals);
//Return empty array if no items found
//http://php.net/manual/en/function.explode.php#114273
return array_diff($vals, array(""));
}
It's good to move things into classes, it enables reuse and also you can use an autoloader to only load in the classes you're actually using, rather than PHP parsing all the code. I'd put the first function in a User class or something (pass the session information in as a parameter, don't access that from inside your class) and the second one maybe in a Utils class or something like that?
I am interested in something google couldn't really help me with...
I know that its possible to use anonymous functions and also store functions in a variable in PHP like that
$function = function myFoo() { echo "bar"; }
and call it using the variable: $function();
So far so good but what if I have a function or method declared somewhere but not saved on intializing?
I have a function that shall expect a callable, of course call_user_func() can help me here but then I need to pass the method name in my callback handler which I think is pretty unsafe because in the moment I add the callback I cant say if it really is a function and exists when I store it.
Thatswhy I would like to realize the following szenario:
This function:
function anyFunction() {
echo "doWhatever...!";
}
should be saved in a variable at a later point in time:
$myOtherFunction = get_registered_func("anyFunction");
I know get_registered_func() doesnt exist but I want to know if this is possible somehow!
With this I could now have another function
function setCallback(callable $theCallbackFunction) { }
And use it like this:
setCallback($myOtherFunction);
This would have a great advantage that an exception / a fatal is thrown when the parameter is no function or does not exist.
So in short, is there a way to store a previously defined, already existing function or method in a variable?
PHP's callable meta type can be:
a string
an array
an anonymous function
Only the latter one is somewhat "type safe", i.e. if you get an anonymous function you know it's something you can call. The other two options are merely formalised informal standards (if that makes sense) which are supported by a few functions that accept callbacks; they're not actually a type in PHP's type system. Therefore there's basically no guarantee you can make about them.
You can only work around this by checking whether the callable you got is, well, callable using is_callable before you execute them. You could wrap this into your own class, for example, to actually create a real callable type.
I see no reason why this shouldn't be possible, other than there not being a PHP function to do it. The anonymous function syntax is newly introduced in PHP, I wouldn'be surprised if it was still a little rough around the edges.
You can always wrap it:
function wrap_function ($callback) {
if (is_callable($callback) === false) {
throw new Exception("nope");
}
return function () {
call_user_func($callback, func_get_args());
}
}
$foo = new Foo();
$ref = wrap_function(array($foo, "bar"));
Not a good way, but maybe this helps you:
function foo($a) {
echo $a;
}
$callFoo = 'foo';
$callFoo('Hello World!'); // prints Hello
I've built a CMS for our company which has a huge number of functions, many of which are related to specific functionality which isn't used on most of the sites we use the CMS for. My goal, then, is to only include the script of a function when it's needed (when the function is called).
Right now I'm simply calling up each function as normal, requiring the file where the actual script of the function is located, and then calling a second function (the same name as the function, but with an underscore prefix) which contains the actual script of the function. For example:
function foo($a,$b) {
require_once "funtions-foo.php";
return _foo($a,$b);
}
This, however, seems a little repetitive to me. What I'm looking for is a way to either 'catch' a functions call and, if its name is in an array of 'included' functions, i'll include the correct file and call the function. For example:
catch_function_call($function,$arg1,$arg2) {
$array = array(
'foo' => 'functions-foo.php',
'bar' => 'functions-bar.php'
);
if($array[$function]) {
require_once $array[$function];
return $function($arg1,$arg2);
}
}
There I'm assuming the 'catch_function_call' function can somehow catch when a function is called. As I know of no such function, however, my second thought was to simply define each of the 'included' functions using variables. For example:
$array = array(
'foo' => 'functions-foo.php',
'bar' => 'functions-bar.php'
);
foreach($array as $function => $file) {
function $function($arg1,$arg2) {
$_function = "_".$function;
require_once $file;
return $_function($arg1,$arg2);
}
}
Of course, this gives me an error as I apparently can't use a variable in the name of a function when defining it. Any thoughts on how to get around this or other solutions for only including a function when it's needed?
You can use __call or __callStatic on an object or class, respectively, which would approximate the functionality you're looking for. You can read some explanation in this thread.
However there's no way to do this in the global function space.
Could this help: http://php.net/manual/en/function.create-function.php ?
Or maybe turn the design to OO and use __call().
Just use include_once before each needed function?
Have you considered grouping your functions into sets and storing them as static methods in objects. Then you can use the __autoload() function and stop worrying about when to include.
So:
class Rarely_Used{
static function foo(){}
static function bar(){}
}
class Only_for_Managers{
static function ohboy(){}
static function punish(){}
}
Why is including all the files such a big problem? As you probably are using APC heavy filesystem access won't be a problem. And apart from that, lookups in the function hash table obviously are slower if there are more functions, but still this most certainly will not be the bottleneck of your application.