This is an interesting question because it is a common template and it is especially important to monitor refactoring.
In a purely functional form, you can use the following code:
function rand_or_min( $value, $key, $country ) { $rand = mt_rand(0,100); if ($rand < $value ) { $rand = $value; } // do something call_user_func( array( $country, 'set_' . $value ), array( $rand ) ); } $arr = array('infrastructure' => 5,'education' => 3,'healthcare' => 80); array_walk( $arr, 'rand_or_min', $country );
Although this works well, I strongly recommend that you use a more object-oriented path. Whenever you see a pattern like the one above, you should think about classes and subclasses. What for? Because there is duplicate behavior and a similar state (variables).
In a more OOP method, this can be implemented as follows:
class SomeBasicBehavior { function __construct( $min = 0 ) { $rand = mt_rand(0,100); if( $rand < $min ) { $rand = $min }; return $rand; } } class Infrastructure extends SomeBasicBehavior { } class Education extends SomeBasicBehavior { } class Healthcare extends SomeBasicBehavior { } $country->set_infrastructure( new Infrastructure() ); $country->set_education( new Education() }; $country->set_healthcare( new Healthcare() };
It is not only more readable, but also much more extensible and easily verifiable. Your βdo somethingβ can be easily implemented as member functions in each class, and their behavior can be split as needed (using the SomeBasicBehavior class) or encapsulated as needed.
source share