Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

php - Creating and invoking an anonymous function in a single statement

A php closure or anonymous function is used to create function without specifying its name.

Is it possible to call them without assigning to identifier as we do in JavaScript ? e.g.

(function(){
    echo('anonymous function');
})();

What is the correct use of use construct while defining anonymous function and what is the status of anonymous function in public method with accessibility to private properties?

$anon_func = 
function($my_param) use($this->object_property){ //use of $this is erroneous here
    echo('anonymous function');
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

PHP 7 added the ability to do this.

This code:

(function() { echo "This works as expected in PHP 7.
"; })();

works as one would expect in PHP 7. (It still doesn't work in any PHP 5.x. release)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...