FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!


adding a function to a class dynamically





Mgccl
I tired and failed...
I don't see anyway of adding a function to a class dynamically. I wrote a class like this
Code:
class bcext{
function __construct(){
    $this->bcext();
}
function bcext($load = 1){
    if($load == 1){
        $dir = scandir('plugin/');
        foreach($dir as $key => $var){
            if($key != 0 && $key != 1){
                include('plugin/'.$var);
    }
}

All the php files in the plugin directory are ones contain functions, like this:

Code:
function foo(){
     echo 'bar';
}

This results of creating an function in the global scope, and not under the class's scope.
So what if I want to create a function dynamically in the class scope?
MrBlueSky
What you want isn't easy to accomplish. You can try to use create_function.

First you put the source of the plugin in a string

$source = get_contents('plugin/'.$var);

Then you extract the function parameters using a regular expression into another string $args.

Next you use some string manipulation to strip of the declaration of the function from $source and also the last '}'.

Now $source looks like:

Code:

echo $bar;


Then you use create_function to create a new function:

Code:

$func = create_function($args, $source);


And you add this function ($func) dynamically to an Object or a Class. I have no idea how you can do this (or if it is even possible without dynamically creating the complete class-definition using eval).

To cut a long story short: ask yourself if it's really worth the trouble. What is the advantage of adding these functions to a class?
riv_
And where are you planning to use this stuff anyways...
I think our code references php5 constructs. Just seems a little odd on Frihost.
I think you CAN dynamically add functions using patterns - maybe the factory methd or some such thing. I;m sure I've read about it.
But to be hones, it was over my head!
Related topics
PHP Validation Class
Tutorial: PHP Installed Modules Dynamic Reference Tool
Search function
writing COM components in Perl
An Example to mySQL class
[Resolved] Object Orientated PHP errors
CSS - CSS Tutorial for skin maker
[c++]Using all the members of a class
Adding textbox dynamically. HELP!
JS Help Needed...
c++ object design help
Database connection class!
HTML
Database not update. Where is my wrong code?
Reply to topic    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.