I solved it with the help of @PatJ’s comment.
add_filter('the_content', function ($content) use ($callback){
if (is_singular() && in_the_loop() && is_main_query()){
$id = get_the_ID();
if (in_array($id, array_values($this->pages))){
ob_start();
$callback();
return ob_get_clean();
}
}
return $content;
}, 1);
Note that in this solution the headers are already sent and only rendering is possible. If we want to send for example a location header to redirect the page, then we need a different solution, which is:
add_action('init', function (){
$id = url_to_postid($_SERVER['REQUEST_URI']);
if (in_array($id, array_values($this->pages)))
$callback();
});
So for example in the init we can do redirection if it is a POST and in the_content we can do rendering if it is a GET request.