note 111265 deleted from functions.anonymous by cmb
| From: | cmb@php.net | Date: | Sun, 11 Aug 2019 11:27:04 +0000 |
| Subject: | note 111265 deleted from functions.anonymous by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-211840@lists.php.net to get a copy of this message | ||
Note Submitter: benkuhl at gmail dot com
----
Beware of scope! $this refers to the class that the function was defined within.
----------- Example #1 - Doesn't work (Notice: Undefined variable: this) -----------
<?php
$callableFunc = function () {
var_dump($this);
};
call_user_func($callableFunc);
?>
----------- Example #2 - Doesn't work (Notice: Undefined variable: this) -----------
<?php
class myClass {
public function execute($func) {
if (is_callable($func)) {
call_user_func($func);
}
}
}
$class = new myClass();
$class->execute(function () {
var_dump($this);
});
?>
----------- Example #3 - Works! -----------
<?php
class myClass {
public function getMyExecutableFunction() {
return function () {
var_dump($this);
};
}
public function execute($func) {
if (is_callable($func)) {
call_user_func($func);
}
}
}
$class = new myClass();
$class->execute($class->getMyExecutableFunction()); //object(myClass)[1]
?>
$this is not available in a static method!