<?php foreach( $page->children() as $item ) : ?>
<div class="test">
<?php my_function('haha', $item); ?>
<?php my_function('hehe', $item); ?>
<?php my_other_function('hoho', $item); ?>
<!-- 10 more functions like this -->
</div>
<?php endforeach; ?>
my_function($str, $item) {
// MAKE ITEM WORK WITHOUT SENDING IT ALL THE TIME
return $item->title() . $str;
}
Maybe it’s not so Kirby specific, but it’s a Kirby template/snippet.
Let’s say I have functions that I want to run over and over with different arguments, but I want to use $item in all of them.
What is the most elegant way of having $item sent to the function without the need to send it over and over? What I can think of is global variable or singleton, but both feels like bad practice.
I don’t think, that I’m a very experienced programmer, but I think, that functions should not have an internal state. Im my view, objects and it’s methods have an internal state, but not functions.
So I would stick with passing the same object every time, the function is called. It also shouldn’t make a difference in performance, of you pass the object per reference.
Otherwise I would create my own class and object with all my functions as methods.
In your solution, it is not clearly visible, which dependencies / real parameters your functions have. I don’t think, that this is a good practice.