Printing 1 to 1000 without loop or conditionals - in PHP

Here's an interesting oo solution based on PHP's overloading:

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;

I'm glad my solution is so popular. Here's a slight improvement that offers some modularity:

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;

print implode("\n", range(1, 1000)); 

<?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();

?>

Tags:

Php