Undefined variable when passing variable to snippet


Trying to split my code while it keeps growing and thought I was doing almost exactly what this example is doing

The Template

$items = page('home’)
          ->filterBy(‘tag’, 'services', ',');


<?php foreach ($items as $item): ?>

    <?php if ($item->share() != '1'): ?>
        <?php snippet(’share-component’, array(‘share-component’ => $item)) ?>
    <?php else: ?>
        …something else
    <?php endif ?>

<?php endforeach ?>

The Snippet (share-component)

 <a href="http://www.facebook.com/sharer.php?u=<?=rawurlencode($item->url());?>" target="blank" title="Share on Facebook"
    …svg icon

Unfortunately this gives me error message that says the variable ($item) is undefined.

Could someone kindly tell me what I’m doing wrong here?

You are passing the variable $item to share-component. But the variable you use in your snippet is not called $share-component but $item.

Correct code:

<?php snippet('share-component', ['item' => $item]) ?>

The key in the array is the name of the variable you use in your snippet, the value is the variable that you pass to the snippet.

So that was the problem.

Thank you so much for your help!