salivan salivan - 27 days ago 7
PHP Question

making an abstract callback method in php and passing arbitrary number of parameters

I had if/else foreach repeating in several methods, so I've decided to abstract it out, but got stuck because of convoluted logic.

enter image description here

each_cpt
method looks like this:

private function each_cpt( $callback ) {

//if ( isset( $cpts ) ) {
//foreach ( $cpts as $cpt ) {
//if ( $cpt['post_type'] == $post_type ) {
return $callback( $cpt );
//}
//}
//}

}


Problem is that sometimes I want to pass additional data from caller to callback. e.g.

/**
*
*
* @since 1.0.0
*/
public function vehicle_post_type_link_id( $url, $post ) {

$this->each_cpt( function( $cpt ){
return home_url( $cpt['slug'] . '/' . $post->ID . '/' );
} );

return $url;

}


Notice I need
$post->ID
inside callback. But this is arbitrary, some other methods won't need
$post->ID
. So how do I make a proper abstract method that deals with my situation?

Answer

You can use PHP use syntax to bind a variable with the closure. The use keyword will make $post available to the function.

function ($cpt) use ($post) {
   return home_url(
       sprintf(
           "%s/%s/",
           $cpt['slug'],
           $post->ID
       )
   );
 }

Note that the $this is automatically binded to the closure starting from PHP 5.4. So if $post was a member variable of the class, it can be used using $this as $this is implicitly bounded to the closure.