Your code was missing several braces, also you your $TestValues
is part of the class, not a global variable.
I fixed the code, however you have to check the math and read the oop tutorial on php's site.
<?php
class Primes {
public $TestValues = array(0, 1, 2, 3, 4);
function IsPrime($number) {
//if number is a number, perform the rest of the tests, else, return -1 (error)
if(is_numeric($number)) {
if($number < 0 || $number > 1024)
return -1;
if($number === 0 || $number === 1 || $number % 2 === 0)
return 0;
//if number has passed all previous tests, mod it by all odd numbers from 3 to its square root rounded up.
for($i = 3; $i <= ceil(sqrt($number)); $i = $i + 2) {
//if any numbers mod 3 to its square root equal 0, return 0, (false, not prime)
if($number % $i == 0)
return 0;
}
//if the number has passed all above requirements, then it is a prime number below 1024.
return 1;
} else {
return -1;
}
}
function test() {
foreach($this->TestValues as $value) {
$t = $this->IsPrime($value);
if($t === 0) {
echo($value . "=> Is not Prime");
} elseif($t === 1) {
echo($value . "=> Is Prime");
} elseif(IsPrime() == -1) {
echo($value . "=> Is an Error");
}
echo "\n";
}
}
}
function main() {
$prime = new Primes();
$prime->test();
}
main();