RE: OOP PHP Issue

I can’t get the code below to work, I think the user has geared it to OOP which is not an area i’m familiar with and no matter what I do to correct the $this-> or public / private it still refuses to work (the aim of the code is to have a number in $userinput which gets checked against the $widgetBatches array for the closest match (i.e. input is 1100 and closest is 1000) this then gets deducted from the input (to leave 100) and the process loops again to check and this time returns 100 as the closest, this process continues until the $userinput reaches 0 or a negative number:

[php]<?php

$userinput = 10000; // Our magic variable - user input

$iterations = 0;

function Widget($userinput)
{
$this->iterations++;
$widgetRequested = $userinput;
$widgetBatches = array(“250”, “500”, “1000”, “2000”);

echo "Iteration " . $iterations;
echo "<br/>";

echo "Widget requested: " . $widgetRequested;
echo "<br/>";

$closest = GetClosest($widgetBatches, $widgetRequested);
echo "Closest: " . $closest;
echo "<br/>";

$widgetRemaining = $widgetRequested - $closest;
echo "Remainder: " . $widgetRemaining;

echo "<hr/>";
if($widgetRemaining > 0)
{
    Widget($widgetRemaining);
}
else
{
    echo "The value is now below or equaling zero: " . $widgetRemaining . "!";
}

}

function GetClosest($array, $value)
{
$lowest = null;
foreach($array as $val)
{
if($lowest == null || abs($value - $lowest) > abs($val - $value))
{
$lowest = $val;
}
}
return $lowest;
}

?>[/php]

Nope that’s procedural code, but $this->iterations++; should be $iterations and just quickly looking over that variable the $iterations = 0; doesn’t seem to be in scope or reference properly. The functions are never called, unless they are called somewhere else?

All the script currently does is to assign 10000 to $userinput and 0 to $iterations.

The $this operator is for class variables, but is out of place in you script, $this doesn’t do anything in it. As Strider mentioned, nothing calls the functions so nothing runs.

Sponsor our Newsletter | Privacy Policy | Terms of Service