在没有循环或条件的情况下打印1到1000 - 在PHP中

Sam*_*Sam 7 php

这里采取的想法- 这次你只能使用PHP.这甚至可能吗?

Exp*_*lls 15

这是一个基于PHP重载的有趣oo解决方案:

class thousand_printer {
   public function __construct() {
      $this->print1();
   }

   public function __call($method, $_) {
      $count = str_replace('print', '', $method);
      echo "$count ";
      $this->{"print" . ++$count}();
   }

   public function print1000() {
      echo "1000\n";
   }
}

new thousand_printer;
Run Code Online (Sandbox Code Playgroud)

我很高兴我的解决方案如此受欢迎.这是一个略微改进,提供了一些模块化:

class printer {
   public function __construct() {
      $this->print1();
   }
   public function __call($method, $_) {
      $count = str_replace('print', '', $method);
      echo "$count ";
      $this->{"print" . ++$count}();
   }
}

class thousand_printer extends printer {
   public function print1001() {}
}

new thousand_printer;
Run Code Online (Sandbox Code Playgroud)


vic*_*LLA 10

print implode("\n", range(1, 1000)); 
Run Code Online (Sandbox Code Playgroud)

  • 好像范围不使用循环?:) (4认同)

mik*_*iku 5

<?php

    class Evil
    {
        function __construct($c) {
            $this->c = $c;
        }

        function __call($name, $args) {
            echo $this->c . "\n";
            $this->c += 1;
            $this->tick();
        }

        // The bomb
        function tick() {
            call_user_func(__NAMESPACE__ .'\Evil::__' . $this->c);
        }

        // 007 
        function __1000() {}
    }

    $devil = new Evil(1);
    $devil->tick();

?>
Run Code Online (Sandbox Code Playgroud)