LoginSignup
9
7

More than 5 years have passed since last update.

ヒアドキュメント内に関数オブジェクトを埋め込む

Posted at

ヒアドキュメント内に関数呼び出しを埋め込みたいのだができないらしい。
オブジェクトのメソッドなら呼べるようだ。

{hoge()}  NG
{$boo->hoge()}   OK

__invoke()を使うといわゆる関数オブジェクトのクラスを定義できる。(>=5.3)
関数をラップする関数オブジェクトで置き換えられたらうれしいかもと、いろいろやってみた。

ラッパークラス

functor.php
<?php
class Func {
    private $callable;

    public function __construct($callable) {
        if (!is_callable($callable)) 
            throw new Exception("not callable");
        $this->callable = $callable;
    }

    public function __invoke() { // >= 5.3
        return call_user_func_array($this->callable, func_get_args());
    }
}

サンプルコード。

<?php

include 'sample.php'

// example
class HogeHelper {
    private $path = "/image";
    function image_tag($file) {
        return "<img src=\"{$this->path}/{$file}\">";
    }
    function __call($name, $args) {
        return "<{$name}>{$args[0]}</{$name}>";
    }
    static function dateformat($date) {
        return date('Y年m月d日', $date);
    } 
}
$helper = new HogeHelper();

// data
$user = (object)array(
  'name' => 'Taro&Bros', 
  'email' => '"Taro" <taro@example.jp>', 
  'icon' => 'taro.jpg', 
  'comment' => "> awsome!\nthanx!",
  'update' => time(),
);

// functors       
$s  = new Func('htmlentities'); // global  function
$br = new Func('nl2br');
$img = new Func( array($helper, 'image_tag')); // instance method
$em = new Func( array($helper, 'em'));    // magic method
$df = new Func('HogeHelper::dateformat'); // static method
$C  = new Func('strval');     // for const value

// here doc
$comment = <<<AAA
<div id="100" class="comment">
<p>{$img($user->icon)}</p>
<p>{$s($user->name)}</p>
<p>{$s($user->email)}</p>
<p>{$br($s($user->comment), false)}</p>
<p>{$em($df($user->update))}</p>
<p>{$C(__FILE__)}</p>
</div>
AAA;

echo $comment;

出力

<div id="100" class="comment">
<p><img src="/image/taro.jpg"></p>
<p>Taro&amp;Bros</p>
<p>&quot;Taro&quot; &lt;taro@example.jp&gt;</p>
<p>&gt; awsome!<br>
thanx!</p>
<p><em>2013年05月31日</em></p>
<p>C:\phpproj\sample.php</p>
</div> 
9
7
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
7