samedi 20 mars 2021

PHP/Laravel - Define function for another class

is there any way to define a function for a specific class/object outside of it?
I made an example using PHP 8 functionalities:

// Call this function somewhere
public function registerFunctions() {

    Magic::createFunction(
        target: A::class,
        visibility: 'public',
        name: 'foo',
        parameters: ['object' => Object::class, 'text' => 'string'],

        closure: function(Object $object, string $text) {
            echo 'This is my class which exists on runtime only: ' . $params['text'];
        }
    );

}

Magic::createFunction will produce an internal function (not visible for humans) like this:

class A {
    
    public function foo(Object $object, string $text) {
         $object->setText($text);
         echo 'Set text to object: ' . $text;
    }
    
}

So I can use:

(new AB())->foo(myObject, 'Hello world!'); // variable "text" in "myObject" was set to 'Hello world.'

I know there'e something like magic methods in PHP, but I have to define them manually inside of t's class. I want to create them out of their class. Could this be done using Reflection or similar tools?

Thanks in advance!





Aucun commentaire:

Enregistrer un commentaire