note 111265 added to functions.anonymous
| From: | benkuhl at gmail dot com | Date: | Thu, 31 Jan 2013 16:34:37 +0000 |
| Subject: | note 111265 added to functions.anonymous | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-193467@lists.php.net to get a copy of this message | ||
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!
----
Server IP: 69.147.83.199
Probable Submitter: 74.143.144.100
----
Manual Page -- http://php.net/manual/en/functions.anonymous.php
Edit -- https://master.php.net/note/edit/111265
Del: integrated -- https://master.php.net/note/delete/111265/integrated
Del: useless -- https://master.php.net/note/delete/111265/useless
Del: bad code -- https://master.php.net/note/delete/111265/bad+code
Del: spam -- https://master.php.net/note/delete/111265/spam
Del: non-english -- https://master.php.net/note/delete/111265/non-english
Del: in docs -- https://master.php.net/note/delete/111265/in+docs
Del: other reasons-- https://master.php.net/note/delete/111265
Reject -- https://master.php.net/note/reject/111265
Search -- https://master.php.net/manage/user-notes.php