jathin
jathin

Reputation: 318

Passing a function as a parameter to another function

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 :)

Upvotes: 0

Views: 87

Answers (2)

Ben Kirchner
Ben Kirchner

Reputation: 303

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.

Upvotes: 2

Marc B
Marc B

Reputation: 360562

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');.

Upvotes: 2

Related Questions