Alexander Solonik
Alexander Solonik

Reputation: 10250

Understanding the parameters passed to the array_reduce method

I was just going through this online tutorial, and I see the below script:

<?php

include_once 'renderer.php';

class Page {
    
    protected $renderers;
    
    public function add($renderer) {
        $this->renderers[] = $renderer;
    }
    
    public function render() {
    
        $content = '';
        $content .= "--Start of page--\n";
        $content .= array_reduce($this->renderers , function($output , $r){
            return $output .= $r->render()."\n";
        } , '');
        $content .= "--End of page--\n";
        
        return $content;
    }
    
}

$page = new Page();

$page->add(new BlogRenderer());
$page->add(new ArticleRenderer());

echo $page->render();

Let's zoom in to the the call to the array_reduce() call:

 $content .= array_reduce($this->renderers , function($output , $r){
                return $output .= $r->render()."\n";
            } , '');

I have 2 really fundamental questions here, what are there two parameters being passed to the array_reduce function and when did render() become a property of $r , for the call to $r->render() to be valid? How is that call valid?

I have seen the PHP manual on the array_reduce method, but the way this method gets used here baffles me.

Upvotes: 0

Views: 280

Answers (1)

Daan
Daan

Reputation: 12246

What are there two parameters being passed to the array_reduce function?

The first parameter is an array with 2 elements (an instance of BlogRenderer() and an instance of ArticleRenderer()).

The second parameter is a callback function.

When did render() become a property of $r?

The callback has 2 parameters, the second parameter $r holds the value of the current iteration. That would be an instance of BlogRenderer() or ArticleRenderer() so in the classes BlogRenderer() and ArticleRenderer() there is a method called render()

I hope this makes sense.

Upvotes: 3

Related Questions