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();
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.
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.
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.
$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.
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:
Bar
must be compatible with the type of Foo
- so just make Bar
extend from Foo
, if possible.
Use unbound functions, like annonymous, static or functions outside of classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With