(Off-topic, but I didn't know where to post this, so...)
I like functional programming, but I also like classes because they
sort of auto-organize the scripts. Here's a piece of code I've come up
to join them. Is there any reason I
shouldn't use this techique (reliability, performance, limitations)? Is
there an easier way of creating new functions on the fly or mapping
functions to static methods?
Basicaly, this code takes a list of class methods and dynamically
(using eval()) creates functions that call those methods. This way you
can keep your helper functions in classes (I use quite a few), but
still be able to call them as functions to keep the code concise.
It also creates a unified class constructor method in PHP4 --
Class::_init().
The other reason I'm playing with this is because I want to tackle the
issue of code generation. I've done some testing and it seems that a
large portion of script processing time is taken by include()/require()
calls. I want to be able to "compile" a whole application into a single
PHP file, and I need to organize my code to allow for that.
<?
class Base {
/** Methods specified here will be exported into global namespace
as functions. */
var $_export = array();
function Base() {
Base_Lang::export(get_class($this), $this->_export);
Base_Lang::call($this, '_init');
}
/** This function is executed at object's creation.
* To be overrided in descending classes. */
function _init () {}
} new Base;
class Base_Lang extends Base {
var $_export = array('export', 'call');
/** Exports class methods (specified with $funcs) into
* global namespace as functions. */
function export ($class, $funcs=array()) {
$php = '';
foreach ($funcs as $func=>$alias) {
if ($func*1==$func) $func = $alias;
if (!function_exists($alias)) {
$php .= "function $func(){ \$args=func_get_args();
return Base_Lang::call('$class','$func',\$args); }\n";
}
}
eval($php);
}
/**
* An alias for call_user_func_array() with simplified syntax
*/
function call ($obj, $fn=false, $params=-1) {
if (is_string($fn)) {
$C = array($obj, $fn);
$P = is_array($params)? $params: array();
}
else {
$C = $obj;
$P = is_array($fn)? $fn: array();
}
return call_user_func_array($C, $P);
}
} new Base_Lang;
class MyTest extends Base {
var $_export = array('foo', 'bar', 'baz'=>'woot');
function foo(){
return 'Ea';
}
function bar(){
return 'sy';
}
function baz(){
return '!';
}
} new MyTest;
// outputs 'Easy!'
print foo().bar().woot();
?>
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Cake
PHP" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at http://groups.google.com/group/cake-php
-~----------~----~----~----~------~----~------~--~---