Using array_map with callable from Trait

In a FrontController I’m using a function to get post meta data & append it to the post:

array_map([$this,'getPostMeta'],$wp_query->posts);

Now I need the same function in other controllers so I moved the getPostMeta-Function in a Trait (Controllers/Partials/PostMetaData.php) and added the use App\Controllers\Partials\PostMetaData; Statement under the use “Sober\Controller…” in the FrontController.

Using a for-loop:

   for($i = 0; $i < $wp_query->post_count; $i++) {
     $wp_query->posts[$i] = PostMetaData::getPostMeta($wp_query->posts[$i]);
    }

everything works fine.

But I can’t get it work using array_map(). I tried:

  • array_map(['PostMetaData::getPostMeta'],$wp_query->posts);

  • array_map(['PostMetaData', 'getPostMeta'], $wp_query->posts);

But none of the above works.

Thanks in advance for any help!

A Trait adds the code it contains to the class in which it is used, so you wouldn’t call it with the name of the trait, you just call it as an method on the class that uses it.
i.e.:

// SomeTrait.php
trait SomeTrait {
  function methodName($arg) { 
    // do something
  }
}

// SomeClass.php
class SomeClass {
  use SomeTrait;

  function doTheThing() {
    return array_map([$this, 'methodName'], $array);
  }
}

Thanks a lot! After some time, because of a self-made problem, everything works fine.

This topic was automatically closed after 42 days. New replies are no longer allowed.