PHP не может переопределить класс

1

Я узнал, что мой предыдущий код (из моего предыдущего вопроса) был слишком медленным, чтобы делать то, что я хотел, поэтому теперь у меня быстрый рабочий код. Я добавил простой код для подсчета. Что касается Невозможно переопределить класс, я прочитал другие вопросы, связанные со ссылкой на.php файл, например require_once (something.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";
}
?>

Как я могу это исправить? (а второй - это код, который не соответствует классу?)

  • 3
    Ваш класс находится внутри в while петли , поэтому повторно объявляет каждый раз через петлю. Убери это.
  • 0
    Использование некоторого простого отступа в коде подсвечивало бы это довольно быстро
Показать ещё 1 комментарий
Теги:
math

1 ответ

1
Лучший ответ

Ваш класс объявлен в while цикл, и он получает повторно объявлен каждую итерацию.

То, что вы, вероятно, имели в виду, - это сделать новый экземпляр каждой итерации.

Это модифицированный код

<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
ini_set("log_errors", 0);

// 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

$numbers = 0;
$amout = 0;

while ($numbers < 50)
{
    $numbers + 1;

    $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";
}
?>

Ещё вопросы

Сообщество Overcoder
Наверх
Меню