PHP pass function name as param then call the function?

Viewed 65650

I need to pass a function as a parameter to another function and then call the passed function from within the function...This is probably easier for me to explain in code..I basically want to do something like this:

function ($functionToBeCalled)
{
   call($functionToBeCalled,additional_params);
}

Is there a way to do that.. I am using PHP 4.3.9

Thanks!

7 Answers

I think you are looking for call_user_func.

An example from the PHP Manual:

<?php
function barber($type) {
    echo "You wanted a $type haircut, no problem";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
?>
function foo($function) {
  $function(" World");
}
function bar($params) {
  echo "Hello".$params;
}

$variable = 'bar';
foo($variable);

Additionally, you can do it this way. See variable functions.

In php this is very simple.

<?php

function here() {
  print 'here';
}


function dynamo($name) {
 $name();
}

//Will work
dynamo('here');
//Will fail
dynamo('not_here');

You could also use call_user_func_array(). It allows you to pass an array of parameters as the second parameter so you don't have to know exactly how many variables you're passing.

If you want to do this inside a PHP Class, take a look at this code:

// Create a sample class
class Sample
{

    // Our class displays 2 lists, one for images and one for paragraphs
    function __construct( $args ) {
        $images = $args['images'];
        $items  = $args['items'];
        ?>
        <div>
            <?php 
            // Display a list of images
            $this->loop( $images, 'image' ); 
            // notice how we pass the name of the function as a string

            // Display a list of paragraphs
            $this->loop( $items, 'content' ); 
            // notice how we pass the name of the function as a string
            ?>
        </div>
        <?php
    }

    // Reuse the loop
    function loop( $items, $type ) {
        // if there are items
        if ( $items ) {
            // iterate through each one
            foreach ( $items as $item ) {
                // pass the current item to the function
                $this->$type( $item ); 
                // becomes $this->image 
                // becomes $this->content
            }
        }
    }

    // Display a single image
    function image( $item ) {
        ?>
        <img src="<?php echo $item['url']; ?>">
        <?php 
    }

    // Display a single paragraph
    function content( $item ) {
        ?>
        <p><?php echo $item; ?></p>
        <?php 
    }
}

// Create 2 sample arrays
$images = array( 'image-1.jpg', 'image-2.jpg', 'image-3.jpg' );
$items  = array( 'sample one', 'sample two', 'sample three' );

// Create a sample object to pass my arrays to Sample
$elements = { 'images' => $images, 'items' => $items }

// Create an Instance of Sample and pass the $elements as arguments
new Sample( $elements );
Related