1
類
我發現我以前的代碼(從我前面的問題)是做什麼,我想,現在我有一個快速運行的代碼太慢。我添加了一個簡單的代碼來計數。至於不能重新聲明類,我看了其中涉及指像require_once(something.php)以.php文件的其他問題,我沒有這以外的任何其他文件。我試圖設置兩個文件,所以我有一個.php文件,但後來我得到了多個錯誤。這是我的代碼。PHP不能重新聲明
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
ini_set("log_errors", 0);
$numbers = 0;
$amout = 0;
while ($numbers < 50) {
$numbers + 1;
// This till end of class is to get the divisor numbers
class Divisors {
public $factor = array();
public function __construct($num) {
$this->num = $num;
}
// count number of divisors of a number
public function countDivisors() {
if ($this->num == 1) return 1;
$this->_primefactors();
$array_primes = array_count_values($this->factor);
$divisors = 1;
foreach($array_primes as $power) {
$divisors *= ++$power;
}
return $divisors;
}
// prime factors decomposer
private function _primefactors() {
$this->factor = array();
$run = true;
while($run && @$this->factor[0] != $this->num) {
$run = $this->_getFactors();
}
}
// get all factors of the number
private function _getFactors() {
if($this->num == 1) {
return ;
}
$root = ceil(sqrt($this->num)) + 1;
$i = 2;
while($i <= $root) {
if($this->num % $i == 0) {
$this->factor[] = $i;
$this->num = $this->num/$i;
return true;
}
$i++;
}
$this->factor[] = $this->num;
return false;
}
} // our class ends here
$example = new Divisors($numbers);
// Here it will check if the divisor has 5 divisors
if ($example->countDivisors() == 5) {
// if true it will add 1 to the amount of numbers with 5 divisors
$amount + 1;
}
}
// when the loop has checked 50 numbers it will print the amount
if ($numbers == 50){
print "There are $amount numbers with 5 divisors";
}
?>
我該如何解決這個問題? (其次是不是類的代碼有效嗎?)
你的類是'while'循環中,因此通過循環每次重新聲明。把它移出來。 – AbraCadaver
使用一些簡單的代碼縮進會很快凸顯這個 – RiggsFolly
當移動出來,我得到;語法錯誤,意外'while'(T_WHILE),期望函數(T_FUNCTION) – VinceD