LoginSignup
9
3

More than 3 years have passed since last update.

PHPのいろんな機能でFizzBuzz

Last updated at Posted at 2019-09-21
1 / 23

この記事はPHPカンファンス北海道2019の懇親会LTのために用意したスライドです。


本日アンカンファレンスで話をしました

image.png


PHPには何だってありますよ

image.png


PHP言語機能

image.png


PHPの制御構造

スクリーンショット 2019-09-21 17.22.45.png


アンカンファレンスではPHPの機能をフル活用したい層と、PHPの進歩を特に望んでいない層の溝が存在する、ということがP++事件の元凶だったという話をしました


とはいえいろんな機能を使えるとコードの表現力の幅は拡がる


PHPのいろんな機能でFizzBuzz


image.png


注意

この発表で仕事で許されうるPHPコードは1行もありません


とはいえまあ、重箱の隅をつつくようなPHPコードが役立つこともありうるかもしれない


for / foreach


FizzBuzzの定番ですね


せっかくなので混ぜちゃいましょう


<?php
foreach (call_user_func(function() {
  $a = [];
  for ($i = 0; $i <= 100; $i++)
    $a[]=$i%3?($i%5?$i:@Fizz):($i%5?@Buzz:@FizzBuzz);
  return$a;
}) as $i) {
  echo $i, PHP_EOL;;
}

class


<?php
trait Fizz { function __toString() { return "Fizz"; } }
trait Buzz { function __toString() { return "Buzz"; } }
trait FizzBuzz { function __toString() { return "FizzBuzz"; } }
trait N { function __toString() { return ltrim(__CLASS__, @_); } }
spl_autoload_register(function ($class) {
    $n = ltrim($class, @_);
    $trait = null;
    if ($n % 3 === 0) $trait .= "Fizz";
    if ($n % 5 === 0) $trait .= "Buzz";
    $trait = $trait ?? 'N';
    eval("final class $class { use $trait; }");
});
foreach (range(1, 100) as $n) {
    $class = "_$n";
    echo new $class, PHP_EOL;
}


require


fizzbuzz.php
<?php global $i ?>
<?= ['FizzBuzz',null,null,'Fizz',null,'Buzz','Fizz',null,
null,'Fizz','Buzz',null,'Buzz',null,null][++$i%15] 
?? $i, PHP_EOL ?>
<?php require 'fizzbuzz.php' ?>
<?php require 'fizzbuzz.php' ?>
... (100回書く)

include


<?php set_error_handler(function ($_, $msg) {
    if (preg_match('/include\((?<n>\d+)\.php\)/', $msg, $m)) {
        if ($m['n'] % 3 === 0): ?>Fizz<?php endif;
        if ($m['n'] % 5 === 0): ?>Buzz<?php endif;
        if ($m['n'] % 3 !== 0 && $m['n'] % 5 !== 0) echo $m['n'];
        ?>

<?php
    };
});

foreach (range(1, 100) as $i) include "$i.php";
9
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
3