Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Object-Oriented PHP Basics Building the Recipe Separating Methods

Alexei Parphyonov
Alexei Parphyonov
34,128 Points

Calling Non-Static Function from withing Render Class

Hello everyone. I am a little bit confused, maybe somebody could explain.

Instead of rendering ingredients as strings inside listIngredients public static function, I added function formatIngredient to the Render class and made it a private function (non-static) expecting to call it from inside the foreach loop inside listIngredients and not making it available from outside class.

private function formatIngredient($ingredient) 
    {
        if ($ingredient['measure'] != null && $ingredient['amount'] != null) {
            return '- ' . $ingredient['amount'] . ' ' . $ingredient['measure'] . ' of ' . $ingredient['item'];
        } else {
            return '- ' . $ingredient['item'] . ' (to taste)';
        }
    }

But when I started to call it from within listIngredients like below, it raised an error. I used $this->formatIngredient($ingredient) since my function is not static, but a private function of a class.

foreach ($ingredients as $index => $ingredient) {
    $output .= $this->formatIngredient($ingredient);
}

And it didn't work. It worked when I used self::formatIngredient($ingredient).

How does it happen? I did not make this function static. It is a simple private function of a class.

Thank you for your help in advance!

jamesjones21
jamesjones21
9,260 Points

Could you show the ingredient variable? As that maybe declared as static?

Alexei Parphyonov
Alexei Parphyonov
34,128 Points

@jamesjones21, not it is not static. It is already there, inside foreach-loop ($ingredients as $index => $ingredient). So it takes items from Recipe class $ingredients array which looks exactly as in the course.

Anyway, here is the addIngredient function without conditionals:

public function addIngredient($item, $amount = null, $measure = null)
    {
        $this->ingredients[] = array(
            'item' => ucwords($item),
            'amount' => ucwords($amount),
            'measure' => strtolower($measure)
        );
    }

$ingredients themselves are private, but as I understood it should not be the case when accessing it from inside class.