Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP binding method to another class

Tags:

php

php-7

Can i bind method of class Foo to class Bar? And why the code below throws a warning "Cannot bind method Foo::say() to object of class Bar"? With function instead of method code works fine.

P.S. I know about extending) it is not practical question, just want to know is it real to bind non-static method to another class

class Foo {

    public $text = 'Hello World!';

    public function say() {
        echo $this->text;
    }

}

class Bar {

    public $text = 'Bye World!';

    public function __call($name, $arguments) {
        $test = Closure::fromCallable(array(new Foo, 'say'));
        $res = Closure::bind($test, $this);
        return $res();
    }

}

$bar = new Bar();
$bar->say();

Code below works fine

 function say(){
    echo $this->text;
 }
 class Bar {

    public $text = 'Bye World!';

    public function __call($name, $arguments) {
        $test = Closure::fromCallable('say');
        $res = Closure::bind($test, $this);
        return $res();
    }

}

$bar = new Bar();
$bar->say();
like image 448
empy26 Avatar asked Nov 07 '17 19:11

empy26


People also ask

How do you call a function outside the class in PHP?

you can use require_once() with exact path of that class after that you should use the object of the included class and function name for calling the function of outer class. Save this answer.

What does :: class do in PHP?

SomeClass::class will return the fully qualified name of SomeClass including the namespace. This feature was implemented in PHP 5.5. It's very useful for 2 reasons. You can use the use keyword to resolve your class and you don't need to write the full class name.

What is PHP bind method?

The PDOStatement::bindParam() function is an inbuilt function in PHP that is used to bind a parameter to the specified variable name. This function bound the variables, pass their value as input, and receives the output value, if any, of their associated parameter marker.

What is the purpose of $this in PHP?

$this is a reserved keyword in PHP that refers to the calling object. It is usually the object to which the method belongs, but possibly another object if the method is called statically from the context of a secondary object. This keyword is only applicable to internal methods.


1 Answers

This is currently not supported. If you want to bind a closure to a new object, it must not be a fake closure, or the new object must be compatible with the old one (source).

So, what is a fake closure: A fake closure is a closure created from Closure::fromCallable.

This means, you have two options to fix your problem:

  1. Bar must be compatible with the type of Foo - so just make Bar extend from Foo, if possible.

  2. Use unbound functions, like annonymous, static or functions outside of classes.

like image 186
Philipp Avatar answered Oct 04 '22 04:10

Philipp