オブジェクト

広告

PHPスクリプトにてクラスを定義し、オブジェクトを作成してテンプレートファイルに渡すことが出来ます。

例えば次のようなクラスを定義してみます。

class Fruit{
  public $name;
  public $price;

  function __construct($name, $price){
    $this->name = $name;
    $this->price = $price;
  }

  public function getPrice(){
    return $this->price;
  }
}

PHPスクリプトでは定義したクラスのオブジェクトを「assign」メソッドの2番目の引数として指定します。例えば次のように記述します。

<?php

$smarty = new Smarty();

$smarty->assign('title', 'Fruit');
$smarty->assign('fruit', new Fruit('Apple', '80'));

$smarty->display('index.tpl');

class Fruit{
  public $name;
  public $price;

  function __construct($name, $price){
    $this->name = $name;
    $this->price = $price;
  }

  public function getPrice(){
    return $this->price;
  }
}

?>

次に値を割り当てられるテンプレートファイル側の記述方法です。PHPスクリプトから渡されたオブジェクトのメンバ変数にアクセスするには次のように記述します。

{$オブジェクト名->メンバ変数}

またオブジェクトのメンバメソッドにアクセスするには次のように記述します。

{$オブジェクト名->メンバメソッド(引数, 引数, ...)}

具体的には次のように記述します。

<html>
<head>
<title>Smarty Test</title>
</head>
<body>

<h1>{$title}</h2>
<p>Name : {$fruit->name}</p>
<p>Price : {$fruit->getPrice()}</p>

</body>
</html>

サンプルプログラム

では簡単なサンプルプログラムを作成して試してみます。

sample4-1.php

<?php

require_once('Smarty.class.php');

$smarty = new Smarty();

$smarty->template_dir = 'd:/smartysample/var/templates/';
$smarty->compile_dir  = 'd:/smartysample/var/templates_c/';
$smarty->config_dir   = 'd:/smartysample/var/configs/';
$smarty->cache_dir    = 'd:/smartysample/var/cache/';

$smarty->assign('title', 'Fruit');
$smarty->assign('fruit', new Fruit('Apple', '80'));

$smarty->display('sample4-1.tpl');

class Fruit{
  public $name;
  public $price;

  function __construct($name, $price){
    $this->name = $name;
    $this->price = $price;
  }

  public function getPrice(){
    return $this->price;
  }
}

?>

上記を「sample4-1.php」の名前で「(Apacheドキュメントルート)¥smarty¥var」に保存します。

sample4-1.tpl

{* Smarty var/sample4-1.tpl *}
<html>
<head>
<title>Smarty Test</title>
</head>
<body>

<h1>{$title}</h1>
<p>Name : {$fruit->name}</p>
<p>Price : {$fruit->getPrice()}</p>

</body>
</html>

上記を「sample4-1.tpl」の名前で「D:¥smartysample¥var¥templates」に保存します。

そしてブラウザから「http://localhost/smarty/var/sample4-1.php」へアクセスして下さい。

オブジェクト

( Written by Tatsuo Ikura )