Iteration  ni uwezo wa kuifanya value yeyote iweze kufanyiwa loop kw akutumia foreach(), 

 

<?php

function printIterable( $myIterable) {

   foreach($myIterable as $item) {

       echo $item;

   }

}

 

$arr = ["a", "b", "c"];

printIterable($arr);

?>

 

 Code hizo hapo juu pia zinaweza kuandikwa katika mtindo huu

<?php

function getIterable() {

   return ["a", "b", "c"];

}

 

$myIterable = getIterable();

foreach($myIterable as $item) {

   echo $item;

}

?>

 

Sasa ngoja tuone kwenye class

Mfano
<?php

class IterableCollection {
    private $items;

    public function __construct() {
        $this->items = ["a", "b", "c"];
    }

    public function getItems() {
        return $this->items;
    }
}

$iterableCollection = new IterableCollection();
$items = $iterableCollection->getItems();

foreach($items as $item) {
    echo $item;
}

?>

 

Mfano mwingine:

Katika mfano huu utajifunza jinsi ya kukokotia factorial of number. 

<?php

 

class FactorialCalculator {

    private $number;

 

    public function __construct($number) {

        $this->number = $number;

    }

 

    public function calculate() {

        $result = 1;

        $numbers = range(1, $this->number);

        

        foreach($numbers as $num) {

            $result *= $num;

        }

        

        return $result;

    }

}

 

// Instantiate the FactorialCalculator class

$factorialCalculator = new FactorialCalculator(6);

 

// Calculate the factorial

$factorial = $factorialCalculator->calculate();

 

// Output the result

echo "Factorial of 6 is: " . $factorial;

 

?>

 

Pia unaweza kutumia reflection class kufanya loop

<?php

class MyClass {

   private $property1 = 'Value 1';

   protected $property2 = 'Value 2';

   public $property3 = 'Value 3';

}

 

$instance = new MyClass();

 

$reflection = new ReflectionClass($instance);

 

foreach ($reflection->getProperties() as $property) {

   $property->setAccessible(true);

   echo $property->getName() . ': ' . $property->getValue($instance) . '<br>';

}

 

Code hizo hapo juu zinaweza pia kuandikw akatika mtindo wa kutumia reflectionclass hii ni njia ambayo inawezesha program yenyewe kujikaguwa na kuweza kutoa taarifa. Hattaizungumzia hii concept hapa.

 

class MyClass {

    private $property1 = 'Value 1';

    protected $property2 = 'Value 2';

    public $property3 = 'Value 3';

}

 

$instance = new MyClass();

 

$reflection = new ReflectionClass($instance);

 

foreach ($reflection->getProperties() as $property) {

    $property->setAccessible(true);

    echo $property->getName() . ': ' . $property->getValue($instance) . '<br>';

}


 

Mwisho:

Huu ndio mwisho wa course yetu ya OOP, katika masomo yatakayofuata ni kufanya pracrical zaidi. Yaani tunakwenda kuifanyia kazi OOP kwenye uhalisia wake kwenye project. Ni matumaini yangu kuwa utaelewa vyema kwenye mazoezi hayo. Ila hakikisha hizi concept tulizojifunza umezipata.