将函数作为参数传递给另一个函数

问题描述:

This code works and there may be better methods to achieve the thing,but my questions are ,

Is there any specific term for passing like this ? (as with anonymous functions ),
is this an acceptable practice ? ,

is it against standards ?

<?php
// suppose the only way i can retrieve the content is by using this function 
//like  wordpress equivalent of the_content()
function mycontent()
{
    $Original_content="oldcontent";
    return $Original_content;
}

//instead of ---> echo $Original_content."facebook,twitter code";
//if i define a new function
function social_share($content)
{
    $added_social=$content;
    $added_social.=" +  facebook,twitter code...";
    echo $added_social;
}

//function call
social_share(mycontent());
?>  

thanks in advance :)

此代码有效,可能有更好的方法来实现,但我的问题是, p> \ n

这样的传递是否有任何特定术语? em> strong>(与匿名函数一样),
是这个 一种可接受的做法 , em> strong> p>

是否符合标准? em> strong> p>

  &lt;?php 
 //假设我可以检索内容的唯一方法是使用此函数
 //喜欢wordpress等效于the_content()
function mycontent()
 {
 $ Original_content =“  oldcontent“; 
返回$ Original_content; 
} 
 
 //而不是---&gt;  echo $ Original_content。“facebook,twitter code”; 
 //如果我定义一个新函数
function social_share($ content)
 {
 $ added_social = $ content; 
 $ added_social。=“+ facebook,twitter  code ...“; 
 echo $ added_social; 
} 
 
 //函数call 
social_share(mycontent()); 
?&gt;  
  code>  pre> 
 
 

提前感谢:) p> div>

You're not passing a function. You're passing the result of one function call directly to another as an argument. 'passing a function' implies that the 'parent' function will be calling the 'child' function at some point. IN this case, social_share does NOT invoke mycontent() at all - that's done long before social_share even executes.

That being said, if you had something like this:

function my_echo($arg) {
   print($arg);
}

function social_share($somearg, $func_to_invoke) {
    $$func_to_invoke($somearg);
}

social_share('hello', 'my_echo');

then you would be invoking one function from another by passing it as an argument. In this case, you'd get "hello" printed out by your little custom my_echo function, without ever having written my_echo('hello');.

Nothing wrong with this at all. This is a lot like object oriented approaches in fact. You can create a class that has these methods and use them to pass other properties to other objects and classes and etc. It's good practice in my opinion.