Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add methods dynamically

Tags:

php

class

I'm trying to add methods dynamically from external files. Right now I have __call method in my class so when i call the method I want, __call includes it for me; the problem is I want to call loaded function by using my class, and I don't want loaded function outside of the class;

Class myClass
{
    function__call($name, $args)
    {
        require_once($name.".php");
    }
}

echoA.php:

function echoA()
{
    echo("A");
}

then i want to use it like:

$myClass = new myClass();
$myClass->echoA();

Any advice will be appreciated.

like image 404
Shadow Walker Avatar asked Aug 11 '11 13:08

Shadow Walker


2 Answers

You cannot dynamically add methods to a class at runtime, period.*
PHP simply isn't a very duck-punchable language.

* Without ugly hacks.

like image 147
deceze Avatar answered Oct 06 '22 00:10

deceze


Is this what you need?

$methodOne = function ()
{
    echo "I am  doing one.".PHP_EOL;
};

$methodTwo = function ()
{
    echo "I am doing two.".PHP_EOL;
};

class Composite
{
    function addMethod($name, $method)
    {
        $this->{$name} = $method;
    }

    public function __call($name, $arguments)
    {
        return call_user_func($this->{$name}, $arguments);
    }
}


$one = new Composite();
$one -> addMethod("method1", $methodOne);
$one -> method1();
$one -> addMethod("method2", $methodTwo);
$one -> method2();
like image 45
Pavel Hanpari Avatar answered Oct 06 '22 00:10

Pavel Hanpari