I have the following PHP class which contains many other app-centric functions beside my_new_iterative_function() but when I enter the foreach the scope of $this (which I need) becomes invalid because of context. What is the correct way to pass the $this so that it is valid inside of method_foo and method_bar.
NOTE: This is part of a more complex issue, and the $fallback_order executes functions in the default sequence, but the my_new_iterative_function() needs to accept an array to control order of execution (which is the purpose of the $order_functions array.
class Foo {
public function my_new_iterative_function(array $fallback_order = array('method_foo', 'method_bar')) {
$order_functions = array(
'method_foo' => function(){
// need to access $this
},
'method_bar' => function(){
// need to access $this
},
);
foreach ( $fallback_order as $index => $this_fallback ) {
$order_functions[$this_fallback]();
}
}
}
$instance_of_foo->my_new_iterative_function();
$instance_of_foo->my_new_iterative_function([ 'method_bar', 'method_foo', ]);
The easiest answer is to pass
$thisin as an argument:$order_functions[$this_fallback]($this);Then you would need to:
No matter what you do you cant actually use
$thisinside those functions like you are inside the class instance because they aren’t part of the class instance. So you’ll need to make sure you have public accessors of some sort for all the properties or functions you need to use from the instance within those functions.