search

Home  >  Q&A  >  body text

php - How to add methods to an instance?

class A(){
}
class B extend A{
    function test(){
        
    }
}

If there is already an instance of class A, how can this instance also be able to use the test method?
Class A cannot be modified

How to do php and python respectively? If possible

When I wrote PHP before, when using other packages, I would encounter that the call result returned was already an instance object, but I expected to add some of my own methods, but the original package did not provide an entry point for injecting dependencies

ps: Convert an instance of A to an instance of B

//我要的就是这样的 magic 函数
a = new A();
function magic(A &a){
    //%^&*$%^#$%^
}
//使得 
get_class(magic(a)) == B   //<===> true

I want to know if there is a grammatical solution to this problem

某草草某草草2781 days ago864

reply all(2)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-06-29 10:09:59

    PHP: Open a new class and use traits, official documentation:
    http://php.net/manual/zh/lang...

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-06-29 10:09:59

    /q/10...

    reply
    0
  • Cancelreply