1

Developing further the class first referred to here.

My aim is to create a class where $inputNumber and $inputArray can be reset, but the methods below don't seem to work.

class myClass
{
public $inputNumber = 27;
public $inputArray = array(1, 2, 4);
public $outputArray = array();

public function setInput($newNumber)
{
    $this->inputNumber = $newNumber;
}

public function setArray($newArray)
{
    $this->inputArray = $newArray;
}

function __construct() {
   $this->outputArray= array($this->inputArray[0]*$this->inputNumber, 
                             $this->inputArray[1]*$this->inputNumber, 
                             $this->inputArray[2]*$this->inputNumber
                             );
}

public function printOutput()
{
    $output = "1st value is " . $this->outputArray[0] . "<br>";
    $output .= "2nd value is " . $this->outputArray[1] . "<br>";
    $output .= "3rd value is " . $this->outputArray[2] . "<br>";
    return $output;
}

}

$obj = new myClass;
$obj = setInput(54);
$obj = setArray(array(6, 12, 24);
echo $obj->printOutput();

1 Answer 1

2

The problem is that outputArray is calculated in the construction of the class, which happens before you've set your input and array.

You should move the calculation logic to its own method, e.g.:

public function calculateOutput()
{
    $this->outputArray= array(
        $this->inputArray[0] * $this->inputNumber, 
        $this->inputArray[1] * $this->inputNumber, 
        $this->inputArray[2] * $this->inputNumber
    );
}

public function printOutput()
{
    // Calculate your result now
    $this->calculateOutput();

    $output = "1st value is " . $this->outputArray[0] . "<br>";
    $output .= "2nd value is " . $this->outputArray[1] . "<br>";
    $output .= "3rd value is " . $this->outputArray[2] . "<br>";
    return $output;
}

Then remove the constructor and your code should work as you have it already.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.