Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,248 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.