declaring a function javascript alike in php?
how can you declare a function like this in php?
class Test {
function __construct(){
$this->method = function($var){ // <-- declaring a functio开发者_开发技巧n javascript alike
echo $var;
};
}
function func(){
if($this->method){
$this->method('test');
}
}
}
$Test = new Test();
$Test->func();
You can do it just like that. Simply put a public $method;
in your class.
Unless you have a specific reason, defining functions in variables is poor practice, as it can be difficult to debug.
You can do that since PHP 5.3, which introduces anonymous functions (closures). See the manual explaing them.
PHP 5.3: http://php.net/manual/en/functions.anonymous.php PHP 5.2 (Ugly solution): http://php.net/manual/en/function.create-function.php
By the way, I see no reason to use anonymous functions in Your code. Just make that function protected method.
精彩评论