首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在php对象中动态添加新方法?

如何在php对象中动态添加新方法?
EN

Stack Overflow用户
提问于 2010-05-30 16:49:12
回答 7查看 61.3K关注 0票数 106

如何将新方法“动态”添加到对象中?

代码语言:javascript
复制
$me= new stdClass;
$me->doSomething=function ()
 {
    echo 'I\'ve done something';
 };
$me->doSomething();

//Fatal error: Call to undefined method stdClass::doSomething()
EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2010-05-30 17:00:05

您可以利用__call实现以下功能:

代码语言:javascript
复制
class Foo
{
    public function __call($method, $args)
    {
        if (isset($this->$method)) {
            $func = $this->$method;
            return call_user_func_array($func, $args);
        }
    }
}

$foo = new Foo();
$foo->bar = function () { echo "Hello, this function is added at runtime"; };
$foo->bar();
票数 102
EN

Stack Overflow用户

发布于 2016-03-05 02:01:19

在PHP7中,您可以使用匿名类,这消除了stdClass的限制。

代码语言:javascript
复制
$myObject = new class {
    public function myFunction(){}
};

$myObject->myFunction();

PHP RFC: Anonymous Classes

票数 57
EN

Stack Overflow用户

发布于 2014-05-01 07:11:09

简单地使用__call来允许在运行时添加新方法有一个主要缺点,那就是这些方法不能使用$this实例引用。一切都很好,直到添加的方法没有在代码中使用$this。

代码语言:javascript
复制
class AnObj extends stdClass
{
    public function __call($closure, $args)
    {
        return call_user_func_array($this->{$closure}, $args);
    }
 }
 $a=new AnObj();
 $a->color = "red";
 $a->sayhello = function(){ echo "hello!";};
 $a->printmycolor = function(){ echo $this->color;};
 $a->sayhello();//output: "hello!"
 $a->printmycolor();//ERROR: Undefined variable $this

为了解决这个问题,你可以这样重写模式

代码语言:javascript
复制
class AnObj extends stdClass
{
    public function __call($closure, $args)
    {
        return call_user_func_array($this->{$closure}->bindTo($this),$args);
    }

    public function __toString()
    {
        return call_user_func($this->{"__toString"}->bindTo($this));
    }
}

通过这种方式,您可以添加可以使用实例引用的新方法

代码语言:javascript
复制
$a=new AnObj();
$a->color="red";
$a->sayhello = function(){ echo "hello!";};
$a->printmycolor = function(){ echo $this->color;};
$a->sayhello();//output: "hello!"
$a->printmycolor();//output: "red"
票数 24
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2938004

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档