Home > Mobile >  Echo keeps previous string
Echo keeps previous string

Time:02-27

EDIT: For more clarity

I need help with understanding why php retains the previous echo information

<?php
    class P {
        private $array = array();

        function primesInRange($a, $b) {
            $string = "";

            array_push($this->array,5);
            array_push($this->array,7);

            for ($i = 0; $i < count($this->array); $i  ) {
                $string.= "$array[$i],";
            }
            return $string;
}

        function testPrimesInRange() {
            echo $this->primesInRange(3,10)."\n";
            echo $this->primesInRange(3,10)."\n";
            echo $this->primesInRange(3,10)."\n";


    }
    $obj = new P;
    $obj->testPrimesInRange(); 


?>

Inside the testPrimesInRange() function,

The first echo prints 5, 7

The second echo prints 5, 7, 5, 7

The third echo prints 5, 7, 5, 7, 5, 7

How do I prevent the previous echos from being printed?

CodePudding user response:

EDIT

One solution could be to reset $this variable as follows: unset($this)

This answer came from How to reset a variable to NULL in PHP?

By clearing the value of $this you solve the issue.

CodePudding user response:

<? php
class P {
    private $array = array();

    function primesInRange($a, $b) {
        $string = "";
        // Add the below statement //
        $this -> array =[];

        array_push($this -> array, 5);
        array_push($this -> array, 7);

        for ($i = 0; $i < count($this -> array); $i  ) {
            $string.= "$array[$i],";
        }
        return $string;
    }

    function testPrimesInRange() {
                echo $this -> primesInRange(3, 10)."\n";
                echo $this -> primesInRange(3, 10)."\n";
                echo $this -> primesInRange(3, 10)."\n";
    }
}

$obj = new P;
$obj -> testPrimesInRange(); 


?>

You should empty the $array variable so that when you call the function "primesInRange" the 5 and 7 will always be pushed to the array and that's why you get the previous data.

  • Related