PHP から割り当てられた変数

PHP から 割り当てられた 変数は、 (php と同様に) 先頭にドル記号 ($) をつける事で参照できます。

例. 割り当てられた変数

php script

  1. <?php
  2. $simplate = new Simplate();
  3. $simplate->assign('firstname', 'Doug');
  4. $simplate->assign('lastname', 'Evans');
  5. $simplate->assign('meetingPlace', 'New York');
  6. $simplate->display('index.tpl');
  7. ?>

一方、index.tpl の内容はこのようになります。

  1. Hello <{$firstname}> <{$lastname}>, glad to see you can make it.
  2. <br />
  3. <{* これは動作しません。変数名は大文字小文字を区別するからです。 *}>
  4. This weeks meeting is in <{$meetingplace}>.
  5. <{* こちらは動作します *}>
  6. This weeks meeting is in <{$meetingPlace}>.

出力は次のようになります。

  1. Hello Doug Evans, glad to see you can make it.
  2. <br />
  3. This weeks meeting is in .
  4. This weeks meeting is in New York.

連想配列

PHP から割り当てられた連想配列を参照することもできます。 この場合は、'.' (ピリオド) 記号の後にキーを指定します。

例. 連想配列の値にアクセスする
  1. <?php
  2. $simplate->assign('Contacts',
  3. array('fax' => '555-222-9876',
  4. 'email' => 'simplate@simplate.example.com',
  5. 'phone' => array('home' => '555-444-3333',
  6. 'cell' => '555-111-1234')
  7. )
  8. );
  9. $simplate->display('index.tpl');
  10. ?>

一方、index.tpl の内容はこのようになります。

  1. <{$Contacts.fax}><br />
  2. <{$Contacts.email}><br />
  3. <{* you can print arrays of arrays as well *}>
  4. <{$Contacts.phone.home}><br />
  5. <{$Contacts.phone.cell}><br />

出力は次のようになります。

  1. 555-222-9876<br />
  2. simplate@simplate.example.com<br />
  3. 555-444-3333<br />
  4. 555-111-1234<br />

配列のインデックス

配列に対してインデックスでアクセスすることもできます。

例. インデックスによって配列にアクセスする
  1. <?php
  2. $simplate->assign('Contacts', array(
  3. '555-222-9876',
  4. 'simplate@simplate.example.com',
  5. array('555-444-3333',
  6. '555-111-1234')
  7. ));
  8. $simplate->display('index.tpl');
  9. ?>

一方、index.tpl の内容はこのようになります。

  1. <{$Contacts.0}><br />
  2. <{$Contacts.1}><br />
  3. <{* you can print arrays of arrays as well *}>
  4. <{$Contacts.2.0}><br />
  5. <{$Contacts.2.1}><br />

出力は次のようになります。

  1. 555-222-9876<br />
  2. simplate@simplate.example.com<br />
  3. 555-444-3333<br />
  4. 555-111-1234<br />

オブジェクト

PHP から割り当てられた オブジェクト のプロパティにアクセスするには、-> 記号の後にプロパティ名を指定します。

例. オブジェクトのプロパティにアクセスする
  1. name: <{$person->name}><br />
  2. email: <{$person->email}><br />

出力は次のようになります。

  1. name: Simplate simplate<br />
  2. email: simplate@simplate.example.com<br />