Sam Sam - 5 months ago 21
PHP Question

Printing 1 to 1000 without loop or conditionals - in PHP

Idea taken from here - this time you can only use PHP.
Is this even possible?

Answer

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;
Comments